Skip to content

Breaking into prodcuer and consumer scripts

Course: Kafka - chapter 5

Lets break our logic down into two saparate files

  • producer.ts
import { Kafka } from "kafkajs";
const kafka = new Kafka({
clientId: "my-app",
brokers: ["localhost:9092"]
})
const producer = kafka.producer();
async function main() {
await producer.connect();
await producer.send({
topic: "quickstart-events",
messages: [{
value: "hi there"
}]
});
}
main();
  • consumer.ts
import { Kafka } from "kafkajs";
const kafka = new Kafka({
clientId: "my-app",
brokers: ["localhost:9092"]
})
const consumer = kafka.consumer({ groupId: "my-app3" });
async function main() {
await consumer.connect();
await consumer.subscribe({
topic: "quickstart-events", fromBeginning: true
})
await consumer.run({
eachMessage: async ({ topic, partition, message }) => {
console.log({
offset: message.offset,
value: message?.value?.toString(),
})
},
})
}
main();
  • Update package.json
"scripts": {
"start": "tsc -b && node dist/index.js",
"produce": "tsc -b && node dist/producer.js",
"consume": "tsc -b && node dist/consumer.js"
},
  • Try starting multiple consumers, and see if each gets back a message for the messages produced Notice we specified a consumer group (my-app3)