35 lines
679 B
JavaScript
35 lines
679 B
JavaScript
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() |