Hatua ya 1: Sakinisha Maktaba ya Kafka kwa Node.js
Fungua saraka ya mradi terminal wako Node.js.
Tekeleza amri ifuatayo ili kusakinisha kafkajs
maktaba, Node.js maktaba ya Apache Kafka: npm install kafkajs
.
Hatua ya 2: Kutuma Ujumbe na Producer in Node.js
Ingiza kafkajs
maktaba na ueleze Kafka Broker usanidi:
const { Kafka } = require('kafkajs');
const kafka = new Kafka({
clientId: 'your-client-id',
brokers: ['broker1:port1', 'broker2:port2'], // Replace with actual addresses and ports
});
Unda producer kutuma ujumbe, na utume ujumbe kwa topic:
const producer = kafka.producer();
const sendMessage = async() => {
await producer.connect();
await producer.send({
topic: 'your-topic',
messages: [{ value: 'Hello Kafka!' }],
});
await producer.disconnect();
};
sendMessage();
Hatua ya 3: Kupokea Ujumbe na Consumer in Node.js
Ingiza kafkajs
maktaba na ufafanue Kafka Broker usanidi(ikiwa haujafanywa tayari):
const { Kafka } = require('kafkajs');
const kafka = new Kafka({
clientId: 'your-client-id',
brokers: ['broker1:port1', 'broker2:port2'], // Replace with actual addresses and ports
});
Unda consumer ili kupokea ujumbe kutoka maalum topic:
const consumer = kafka.consumer({ groupId: 'your-group-id' });
const consumeMessages = async() => {
await consumer.connect();
await consumer.subscribe({ topic: 'your-topic', fromBeginning: true });
await consumer.run({
eachMessage: async({ topic, partition, message }) => {
console.log(`Received message: ${message.value}`);
},
});
};
consumeMessages();
Kumbuka: Badilisha maadili kama 'your-client-id'
, 'broker1:port1'
, 'your-topic'
, na 'your-group-id'
uweke maelezo yako halisi ya mradi.
Hakikisha kuwa umerejelea hati rasmi Apache Kafka na kafkajs
maktaba kwa maelezo zaidi kuhusu chaguo za usanidi na utendakazi.