-
Notifications
You must be signed in to change notification settings - Fork 3
/
consumer.js
67 lines (56 loc) · 1.88 KB
/
consumer.js
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
63
64
65
66
67
/**
* Kafka consumer code based on Kafka JS
*/
console.log("Kokpit: Kafka consumer");
const { Kafka } = require('kafkajs');
module.exports = async function consumer(broker, group, topicName, io) {
console.log("Kokpit: Starting Kafka consumer with " + broker + " topic as " + topicName + " group as " + group);
//setup
const kafka = new Kafka({
clientId: 'kokpit-talking',
brokers: [broker]
});
const consumer = kafka.consumer({ groupId: group });
//connect
try
{
await consumer.connect();
io.sockets.emit('connected', "Connected");
}
catch (error)
{
console.log("Error: ***Kokpit Consumer Couldn't connect to Kafka broker");
io.sockets.emit('error', "Error: Consumer couldn't connect to Kafka broker");
return;
}
console.log("Kokpit: Kafka consumer connected");
//subscribe
try
{
await consumer.subscribe({ topic: topicName, fromBeginning: true });
io.sockets.emit('status', "Subscribed");
}
catch (error)
{
console.log("Error: ***Kokpit Consumer couldn't subscribe to topic");
io.sockets.emit('error', "Error: Consumer couldn't subscribe to topic");
return;
}
console.log("Kokpit: Kafka consumer subscribed");
console.log("Kokpit: consuming...");
//consuming
try
{
await consumer.run({
eachMessage: async ({ topic, partition, message }) => {
console.log("Kokpit: consumer received message - "+message.value.toString());
io.sockets.emit('message', message.value.toString());
},
});
}
catch (error)
{
console.log("Error: ***Kokpit Consumer couldn't consume message");
io.sockets.emit('error', "Error: Consumer couldn't consume message");
}
}