forked from oslabs-beta/Kafka-Kare
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproducer.js
More file actions
32 lines (28 loc) 路 848 Bytes
/
Copy pathproducer.js
File metadata and controls
32 lines (28 loc) 路 848 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const { Kafka } = require("kafkajs");
const CHANCE_MESSAGE_SEND = 0.6;
const kafka = new Kafka({
clientId: "my-producer",
brokers: ["localhost:9093"],
});
const topic = "test-topic";
const producer = kafka.producer();
const produceMessages = async () => {
await producer.connect();
setInterval(async () => {
try {
if (Math.random() < CHANCE_MESSAGE_SEND) {
const message = { value: `Message from producer at ${new Date().toISOString()}` };
console.log(`Sending message: ${message.value}`);
await producer.send({
topic,
messages: [message],
});
}
} catch (error) {
console.error("Error producing message", error);
}
}, 1000); // Send a message every second
};
produceMessages().catch((error) => {
console.error("Error in producer script", error);
});