kafkajs/producer.js

35 lines
679 B
JavaScript
Raw Permalink Normal View History

2023-04-12 17:42:55 +00:00
const { Kafka, Partitioners } = require('kafkajs')
const kafka = new Kafka({
clientId: 'my-app',
brokers: ['localhost:9092']
})
const producer = kafka.producer({ createPartitioner: Partitioners.LegacyPartitioner });
const run = async () => {
const obj = {
id: 1,
name: 'John 1',
age: 30
};
// Producing
try {
await producer.connect()
await producer.send({
topic: process.env.TOPIC,
messages: [
{ value: JSON.stringify(obj) },
],
})
console.log('Message sent successfully!');
} catch (error) {
console.error('Error sending message:', error);
} finally {
await producer.disconnect();
}
}
run()