-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspawnConsumer.ts
More file actions
78 lines (67 loc) · 1.83 KB
/
Copy pathspawnConsumer.ts
File metadata and controls
78 lines (67 loc) · 1.83 KB
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
75
76
77
78
import { Kafka } from "kafkajs";
export async function spawnConsumer(
kafka: Kafka,
messageProcessor: (kafkaMessage: any) => void,
groupId: string,
topic: string
) {
const consumer = kafka.consumer({
groupId: groupId,
});
try {
consumer.on(consumer.events.DISCONNECT, (event) => {
console.error(
`${topic} Consumer disconnected: ${JSON.stringify(event)}`
);
});
consumer.on(consumer.events.CRASH, async (event) => {
console.error(
`${topic} Consumer crashed: ${JSON.stringify(event)}`
);
});
consumer.on(consumer.events.STOP, (event) => {
console.error(
`${topic} Consumer stopped: ${JSON.stringify(event)}`
);
});
await consumer.connect();
await consumer.subscribe({ topic });
await consumer.run({
partitionsConsumedConcurrently: 1,
autoCommit: false,
eachMessage: async ({ message, partition }) => {
const kafkaMessage: any = JSON.parse(
message.value!.toString()
);
const { objectId } = kafkaMessage;
console.log(
`MESSAGE ${partition}:${message.offset} RECEIVED!`
);
console.log({
partition: partition,
offset: message.offset,
objectId,
});
messageProcessor(kafkaMessage)
try {
await consumer.commitOffsets([
{
topic: topic,
partition: partition,
offset: message.offset,
},
]);
console.log(
`OFFSET ${partition}:${message.offset} committed`
);
} catch (error) {
console.error(
`Error committing offset for ${objectId}: ${error}`
);
}
},
});
} catch (error) {
console.error(`Error running evaluations consumer: ${error}`);
}
}