Langkah 1: Instal Pustaka Kafka kanggo Node.js
Bukak a ing direktori proyek terminal sampeyan. Node.js
Jalanake printah ing ngisor iki kanggo nginstal kafkajs
perpustakaan, Node.js perpustakaan kanggo Apache Kafka: npm install kafkajs
.
Langkah 2: Ngirim Pesen karo Producer ing Node.js
Impor kafkajs
perpustakaan lan nemtokake Kafka Broker konfigurasi:
const { Kafka } = require('kafkajs');
const kafka = new Kafka({
clientId: 'your-client-id',
brokers: ['broker1:port1', 'broker2:port2'], // Replace with actual addresses and ports
});
Nggawe producer kanggo ngirim pesen, lan ngirim pesen menyang 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();
Langkah 3: Nampa Pesen karo Consumer ing Node.js
Impor kafkajs
perpustakaan lan nemtokake Kafka Broker konfigurasi(yen durung rampung):
const { Kafka } = require('kafkajs');
const kafka = new Kafka({
clientId: 'your-client-id',
brokers: ['broker1:port1', 'broker2:port2'], // Replace with actual addresses and ports
});
Nggawe consumer kanggo nampa pesen saka tartamtu 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();
Cathetan: Ganti angka kaya 'your-client-id'
, 'broker1:port1'
, 'your-topic'
, lan 'your-group-id'
informasi proyek sing nyata.
Priksa manawa kanggo deleng dokumentasi resmi Apache Kafka lan kafkajs
perpustakaan kanggo informasi luwih lengkap babagan opsi konfigurasi lan fungsi.