-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproducer.js
65 lines (53 loc) · 1.58 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
const { Kafka, CompressionTypes, logLevel } = require('kafkajs')
// const host = process.env.HOST_IP || ip.address()
const kafka = new Kafka({
logLevel: logLevel.DEBUG,
brokers: [`localhost:9092`],
clientId: 'example-producer',
})
const topic = 'topic-test'
const producer = kafka.producer()
const getRandomNumber = () => Math.round(Math.random(10) * 1000)
const createMessage = num => ({
key: `key-${num}`,
value: `value-${num}-${new Date().toISOString()}`,
})
const sendMessage = () => {
return producer
.send({
topic,
compression: CompressionTypes.GZIP,
messages: Array(getRandomNumber())
.fill()
.map(_ => createMessage(getRandomNumber())),
})
.then(console.log)
.catch(e => console.error(`[example/producer] ${e.message}`, e))
}
const run = async () => {
await producer.connect()
setInterval(sendMessage, 3000)
}
run().catch(e => console.error(`[example/producer] ${e.message}`, e))
const errorTypes = ['unhandledRejection', 'uncaughtException']
const signalTraps = ['SIGTERM', 'SIGINT', 'SIGUSR2']
errorTypes.forEach(type => {
process.on(type, async () => {
try {
console.log(`process.on ${type}`)
await producer.disconnect()
process.exit(0)
} catch (_) {
process.exit(1)
}
})
})
signalTraps.forEach(type => {
process.once(type, async () => {
try {
await producer.disconnect()
} finally {
process.kill(process.pid, type)
}
})
})