-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkafka-service.js
74 lines (63 loc) · 2.3 KB
/
kafka-service.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
69
70
71
72
73
74
const { Kafka, Partitioners } = require('kafkajs');
const { KAFKA_AUTH_MECHANISM, KAFKA_CLIENT_USERNAME, KAFKA_CLIENT_PASSWORD, KAFKA_CLIENT_ID, KAFKA_BROKERS } = require('./app-references');
class KafkaService {
constructor(role, partition = []) {
console.info(`Kafka Service: ${role}:${partition.length > 0 ? partition : 'partition-off'}`);
if (role === 'producer') {
this.producer = new Kafka({
brokers: KAFKA_BROKERS.split(','),
clientId: KAFKA_CLIENT_ID,
sasl: {
mechanism: KAFKA_AUTH_MECHANISM,
username: KAFKA_CLIENT_USERNAME,
password: KAFKA_CLIENT_PASSWORD,
}
}).producer({ createPartitioner: Partitioners.LegacyPartitioner });
} else if (role === 'consumer') {
this.partition = partition;
this.queue = [];
this.consumer = new Kafka({
brokers: KAFKA_BROKERS.split(','),
clientId: KAFKA_CLIENT_ID,
sasl: {
mechanism: KAFKA_AUTH_MECHANISM,
username: KAFKA_CLIENT_USERNAME,
password: KAFKA_CLIENT_PASSWORD,
}
}).consumer({ groupId: 'test-group' });
}
}
// PRODUCER METHODS
async connect() {
console.info('Producer disconnects from the broker!');
await this.producer.connect();
}
async disconnect() {
console.info('Producer disconnects from the broker!');
await this.producer.disconnect();
}
async send({ topic, messages }) {
console.info('Sending messages to the broker');
await this.producer.send({ topic, messages })
}
// CONSUMER METHOD
async subscribe() {
console.info('Consumer connecting to the broker ...');
await this.consumer.connect();
console.info('Consumer subscribing to the broker ...');
await this.consumer.subscribe({ topic: 'fundTransfers', fromBeginning: true });
console.info('Consumer attempting to start ...');
await this.consumer.run({
eachMessage: async ({ topic, partition, message }) => {
this.queue.push([topic, partition, message.value.toString()]);
console.table(this.queue);
// Temporarily exclude partition matching
// if (this.partition.includes(partition)) {
// this.queue.push([topic, message.value.toString()]);
// console.table(this.queue);
// }
},
})
}
}
module.exports = KafkaService;