-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathproducer.js
68 lines (56 loc) · 1.61 KB
/
producer.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
68
/**
* Kafka producer code based on Kafka JS
*/
//setup
console.log("Kokpit: Kafka producer");
const { Kafka } = require('kafkajs');
module.exports = async function producer(broker, topicName, message, res) {
console.log("Kokpit: Kafka producer with " + broker + " topic as " + topicName + "message as " + message);
//initialize
const kafka = new Kafka({
clientId: 'kokpit-talking',
brokers: [broker]
});
const producer = kafka.producer();
res.writeHead(200, { 'Content-Type': 'text/plain' });
//connect
try
{
await producer.connect();
res.write("Connected");
}
catch (error) {
console.log("Error: ***Kokpit Producer Couldn't connect to Kafka broker");
res.end("Error: Couldn't connect to Kafka broker");
return;
}
console.log("Kokpit: publishing message...");
//publish message
try
{
await producer.send({
topic: topicName,
messages: [
{ value: message },
],
});
console.log("Kokpit: message published");
res.end("Message - " + message + " published");
}
catch (error)
{
console.log("Error: ***Kokpit Producer Couldn't publish");
res.end("Error: Couldn't publish message");
return;
}
//disconnect
try
{
await producer.disconnect();
}
catch (error)
{
console.log("Error: ***Kokpit Producer Couldn't disconnect");
res.end("Error: Couldn't publish disconnect");
}
}