Aika & Karɓar Saƙonni tare da Apache Kafka shiga Node.js

Mataki 1: Shigar Kafka Library don Node.js

Bude terminal a cikin kundin aikin ku Node.js.

Gudun umarni mai zuwa don shigar da kafkajs ɗakin karatu, Node.js ɗakin karatu don Apache Kafka: npm install kafkajs.

Mataki 2: Aika Saƙonni tare da Producer shiga Node.js

Shigo da kafkajs ɗakin karatu kuma ayyana Kafka Broker tsarin daidaitawa:

const { Kafka } = require('kafkajs');  
  
const kafka = new Kafka({  
  clientId: 'your-client-id',  
  brokers: ['broker1:port1', 'broker2:port2'], // Replace with actual addresses and ports  
});  

Ƙirƙiri producer don aika saƙonni, kuma aika saƙo zuwa 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();  

Mataki na 3: Karɓar Saƙonni tare da Consumer shiga Node.js

Shigo da kafkajs ɗakin karatu kuma ayyana Kafka Broker tsarin(idan ba a riga an yi ba):

const { Kafka } = require('kafkajs');  
  
const kafka = new Kafka({  
  clientId: 'your-client-id',  
  brokers: ['broker1:port1', 'broker2:port2'], // Replace with actual addresses and ports  
});  

Ƙirƙiri consumer don karɓar saƙonni daga takamaiman 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();  

Lura: Maye gurbin dabi'u kamar 'your-client-id', 'broker1:port1', 'your-topic', da 'your-group-id' tare da ainihin bayanan aikin ku.

Tabbatar da komawa zuwa takaddun hukuma na Apache Kafka da kafkajs ɗakin karatu don ƙarin bayani game da zaɓuɓɓukan daidaitawa da ayyuka.