-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransaction-producer.js
68 lines (56 loc) · 1.52 KB
/
transaction-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
const { Kafka } = require('kafkajs')
// kafka client
const kafka = new Kafka({
clientId: "transaction-producer-application",
brokers: ['localhost:9092']
})
const startProducer = async () => {
// kafka producer
const producer = kafka.producer({
idempotent: true,
maxInFlightRequests: 1,
transactionalId: 'someId',
});
await producer.connect();
const transaction = await producer.transaction();
try {
await producer.send({
topic: 'topic-transaction',
messages:[
{
key: "transaction1",
value: "Transaction producer demo",
},
],
});
await transaction.commit();
await producer.disconnect();
}catch(e) {
console.log("err in transaction: ", e);
await transaction.abort();
}
}
const startConsumer = async () => {
const consumer = kafka.consumer({
groupId: "simple-group2",
});
await consumer.connect();
await consumer.subscribe({
topic: "topic-transaction",
fromBeginning: true
});
await consumer.run({
eachMessage: async ({ topic, partition, message }) => {
console.log({
value: message.value.toString(),
key: message.key.toString(),
topic:topic,
partition
})
},
})
}
startProducer().then(() => {
console.log("producer run successfully!");
startConsumer();
})