Nggabungake Apache Kafka menyang Node.js proyek ngidini sampeyan nggawe aplikasi wektu nyata sing nggunakake kemampuan pangolahan data Kafka. Mangkene pandhuan dhasar babagan cara nggabungake Apache Kafka menyang Node.js proyek:
Langkah 1: Instal Pustaka Kafka kanggo Node.js
Bukak terminal ing Node.js direktori proyek sampeyan.
Jalanake printah ing ngisor iki kanggo nginstal kafkajs
perpustakaan, Node.js perpustakaan kanggo Apache Kafka: npm install kafkajs
.
Langkah 2: Tulis Kode kanggo Interaksi karo Kafka ing Node.js
Impor kafkajs
perpustakaan menyang kode sampeyan Node.js:
const { Kafka } = require('kafkajs');
Netepake parameter konfigurasi kanggo Kafka Broker:
const kafka = new Kafka({
clientId: 'your-client-id',
brokers: ['broker1:port1', 'broker2:port2'], // Replace with actual addresses and ports
});
Nggawe producer kanggo ngirim pesen:
const producer = kafka.producer();
const sendMessage = async() => {
await producer.connect();
await producer.send({
topic: 'your-topic',
messages: [{ value: 'Hello Kafka!' }],
});
await producer.disconnect();
};
sendMessage();
Nggawe consumer kanggo nampa pesen:
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();
Cathetan: Ganti angka kaya 'your-client-id'
, 'broker1:port1'
, 'your-topic'
, lan 'your-group-id'
informasi proyek sing nyata.
Elinga yen nggabungake Apache Kafka bisa Node.js dadi luwih rumit adhedhasar syarat khusus sampeyan. Priksa manawa kanggo deleng dokumentasi resmi Apache Kafka lan kafkajs
perpustakaan kanggo ngerti liyane babagan opsi konfigurasi lan fungsi.