-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathindex.js
More file actions
62 lines (53 loc) · 1.4 KB
/
index.js
File metadata and controls
62 lines (53 loc) · 1.4 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { Kafka } from 'kafkajs';
import eventType from '../eventType.js';
// KafkaJS-based producer replacing node-rdkafka
const kafka = new Kafka({
clientId: 'node-kafka-producer',
brokers: ['localhost:9092'],
});
const producer = kafka.producer();
async function sendRandomMessage() {
const category = getRandomAnimal();
const noise = getRandomNoise(category);
const event = { category, noise };
try {
await producer.send({
topic: 'test',
messages: [
{ value: eventType.toBuffer(event) }
],
});
console.log(`message sent (${JSON.stringify(event)})`);
} catch (error) {
console.error('Failed to send message', error);
}
}
function getRandomAnimal() {
const categories = ['CAT', 'DOG'];
return categories[Math.floor(Math.random() * categories.length)];
}
function getRandomNoise(animal) {
if (animal === 'CAT') {
const noises = ['meow', 'purr'];
return noises[Math.floor(Math.random() * noises.length)];
} else if (animal === 'DOG') {
const noises = ['bark', 'woof'];
return noises[Math.floor(Math.random() * noises.length)];
} else {
return 'silence..';
}
}
async function start() {
await producer.connect();
console.log('producer ready..');
setInterval(sendRandomMessage, 3000);
}
start();
// Graceful shutdown
process.on('SIGINT', async () => {
try {
await producer.disconnect();
} finally {
process.exit(0);
}
});