31
loading...
This website collects cookies to deliver better user experience
npm init -y
and when this was done I installed our only dependency, KafkaJS using npm install kafkajs
.index.js
and added the familiar script "start": "node index.js",
const { Kafka } = require('kafkajs')
async function run() {
const kafka = new Kafka({
clientId: 'marvel-consumer',
brokers: ['localhost:29092']
})
const consumer = kafka.consumer({ groupId: 'marvel-consumers' })
await consumer.connect()
await consumer.subscribe({ topic: 'marvel' })
await consumer.run({
eachMessage: async ({ topic, partition, message }) => {
console.log('marvel-consumer', {
topic,
partition,
key: message.key.toString(),
value: message.value.toString(),
headers: message.headers,
})
},
})
};
run();
marvel
and writes the published message to the console.const { Kafka } = require('kafkajs')
async function run() {
const kafka = new Kafka({
clientId: 'superhero-consumer',
brokers: ['localhost:29092']
})
const consumer = kafka.consumer({ groupId: 'superhero-consumers' })
await consumer.connect()
await consumer.subscribe({ topic: 'marvel' })
await consumer.subscribe({ topic: 'dc' })
await consumer.run({
eachMessage: async ({ topic, partition, message }) => {
console.log('superhero-consumer', {
topic,
partition,
key: message.key.toString(),
value: message.value.toString(),
headers: message.headers,
})
},
})
};
run();
npm start
for each of these defined consumers and I was ready to process messages, so I needed to create a producer (or two)./producers
and ran through the same steps to create a new node project as we did for the consumers. But this time the index.js
saw some different code:const { Kafka } = require('kafkajs')
async function run() {
const kafka = new Kafka({
clientId: 'dc-producer',
brokers: ['localhost:29092']
})
const topic = 'dc'
const producer = kafka.producer()
await producer.connect()
await producer.send({
topic,
messages: [
{ key: 'batman', value: 'bruce wayne' },
],
})
process.exit(0);
}
run();
npm start
command I then saw messages pop into the superheroes and the 'dc' consumers at the same time.