-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathconfig.js
43 lines (39 loc) · 1 KB
/
config.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
import { Kafka } from "kafkajs";
class KafkaConfig {
constructor() {
this.kafka = new Kafka({
clientId: "nodejs-kafka",
brokers: ["localhost:9093"],
});
this.producer = this.kafka.producer();
this.consumer = this.kafka.consumer({ groupId: "test-group" });
}
async produce(topic, messages) {
try {
await this.producer.connect();
await this.producer.send({
topic: topic,
messages: messages,
});
} catch (error) {
console.error(error);
} finally {
await this.producer.disconnect();
}
}
async consume(topic, callback) {
try {
await this.consumer.connect();
await this.consumer.subscribe({ topic: topic, fromBeginning: true });
await this.consumer.run({
eachMessage: async ({ topic, partition, message }) => {
const value = message.value.toString();
callback(value);
},
});
} catch (error) {
console.error(error);
}
}
}
export default KafkaConfig;