Kuunganishwa Apache Kafka katika Node.js Mradi

Kujumuisha Apache Kafka katika Node.js mradi hukuruhusu kuunda programu za wakati halisi zinazoboresha uwezo wa kuchakata data wa Kafka. Hapa kuna mwongozo wa kimsingi wa jinsi ya kujumuisha Apache Kafka katika Node.js mradi:

Hatua ya 1: Sakinisha Maktaba ya Kafka kwa Node.js

Fungua terminal kwenye Node.js saraka ya mradi wako.

Tekeleza amri ifuatayo ili kusakinisha kafkajs maktaba, Node.js maktaba ya Apache Kafka: npm install kafkajs.

Hatua ya 2: Andika Msimbo wa Kuingiliana na Kafka katika Node.js

Ingiza kafkajs maktaba kwenye Node.js nambari yako:

const { Kafka } = require('kafkajs');

Fafanua vigezo vya usanidi kwa Kafka Broker:

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

Unda producer kutuma ujumbe:

const producer = kafka.producer();  
  
const sendMessage = async() => {  
  await producer.connect();  
  await producer.send({  
    topic: 'your-topic',  
    messages: [{ value: 'Hello Kafka!' }],  
  });  
  await producer.disconnect();  
};  
  
sendMessage();  

Unda ili consumer kupokea ujumbe:

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.

Kumbuka kuwa kujumuisha Apache Kafka kunaweza Node.js kuwa ngumu zaidi kulingana na mahitaji yako maalum. Hakikisha kuwa umerejelea hati rasmi Apache Kafka na kafkajs maktaba ili kuelewa zaidi kuhusu chaguo za usanidi na utendakazi.