-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
example.ts
46 lines (37 loc) · 1.14 KB
/
example.ts
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
import {Kafka, logLevel} from 'kafkajs'
import {faker} from '@faker-js/faker'
const EXAMPLE_TOPIC = 'example-topic'
const EXAMPLE_CONSUMER = 'example-consumer'
const KAFKA_BROKER_ADDRESS = process.env.KAFKA_BROKER!
const kafka = new Kafka({brokers: [KAFKA_BROKER_ADDRESS], logLevel: logLevel.ERROR})
const producer = kafka.producer()
const consumer = kafka.consumer({groupId: EXAMPLE_CONSUMER})
async function main() {
await producer.connect()
await consumer.connect()
await consumer.subscribe({topic: EXAMPLE_TOPIC})
await consumer.run({
eachMessage: async ({message}) => {
console.log({
offset: message.offset,
value: message.value?.toString(),
key: message.key?.toString(),
})
},
})
process.on('SIGTERM', async () => {
await consumer.disconnect()
await producer.disconnect()
process.exit(0)
})
while (true) {
await new Promise(async (res) => {
await producer.send({
topic: EXAMPLE_TOPIC,
messages: [{key: faker.internet.userName(), value: faker.internet.emoji()}],
})
setTimeout(() => res(null), 3 * Math.random() * 1000)
})
}
}
main()