50 lines
1.0 KiB
JavaScript
50 lines
1.0 KiB
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();
|
|
}
|
|
|
|
// Consuming
|
|
// await consumer.connect()
|
|
// await consumer.subscribe({ topic: 'test-topic', fromBeginning: true })
|
|
|
|
// await consumer.run({
|
|
// eachMessage: async ({ topic, partition, message }) => {
|
|
// console.log({
|
|
// partition,
|
|
// offset: message.offset,
|
|
// value: message.value.toString(),
|
|
// })
|
|
// },
|
|
|
|
// })
|
|
}
|
|
|
|
run() |