Haɗin kai Apache Kafka cikin Node.js aikin yana ba ku damar gina aikace-aikacen lokaci-lokaci waɗanda ke amfani da damar sarrafa bayanan Kafka. Anan ga ainihin jagora kan yadda ake haɗawa Apache Kafka cikin Node.js aiki:
Mataki 1: Shigar Kafka Library don Node.js
Bude tasha a cikin Node.js kundin tsarin aikin ku.
Gudun umarni mai zuwa don shigar da kafkajs
ɗakin karatu, Node.js ɗakin karatu don Apache Kafka: npm install kafkajs
.
Mataki 2: Rubuta lamba don hulɗa tare da Kafka a ciki Node.js
Shigo kafkajs
ɗakin karatu cikin Node.js lambar ku:
const { Kafka } = require('kafkajs');
Ƙayyade sigogin daidaitawa don Kafka Broker:
const kafka = new Kafka({
clientId: 'your-client-id',
brokers: ['broker1:port1', 'broker2:port2'], // Replace with actual addresses and ports
});
Ƙirƙiri don producer aika saƙonni:
const producer = kafka.producer();
const sendMessage = async() => {
await producer.connect();
await producer.send({
topic: 'your-topic',
messages: [{ value: 'Hello Kafka!' }],
});
await producer.disconnect();
};
sendMessage();
Ƙirƙiri consumer don karɓar saƙonni:
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();
Lura: Maye gurbin dabi'u kamar 'your-client-id'
, 'broker1:port1'
, 'your-topic'
, da 'your-group-id'
tare da ainihin bayanan aikin ku.
Ka tuna cewa haɗawa Apache Kafka cikin Node.js na iya zama mafi rikitarwa dangane da takamaiman buƙatun ku. Tabbatar da komawa zuwa takaddun hukuma na Apache Kafka da kafkajs
ɗakin karatu don ƙarin fahimta game da zaɓuɓɓukan daidaitawa da ayyuka.