Run a Pulsar end-to-end example
masterThis example demonstrates how to initialize a client, create a producer to send a message, and create a consumer to receive and acknowledge that message.
Workflow:
- Initialize
Pulsar.Clientwith aserviceUrl. - Create a producer using
client.createProducer()specifying atopic. - Subscribe to a topic using
client.subscribe()specifying atopicandsubscriptionname. - Send data using
producer.send()with aBuffer. - Receive data using
consumer.receive(). - Acknowledge the message with
consumer.acknowledge(msg). - Close all resources:
producer,consumer, andclient.
Note: This example assumes a Pulsar server is running at pulsar://localhost:6650.
const Pulsar = require('pulsar-client');
(async () => {
// Create a client
const client = new Pulsar.Client({
serviceUrl: 'pulsar://localhost:6650'
});
// Create a producer
const producer = await client.createProducer({
topic: 'persistent://public/default/my-topic',
});
// Create a consumer
const consumer = await client.subscribe({
topic: 'persistent://public/default/my-topic',
subscription: 'sub1'
});
// Send a message
producer.send({
data: Buffer.from("hello")
});
// Receive the message
const msg = await consumer.receive();
console.log(msg.getData().toString());
consumer.acknowledge(msg);
await producer.close();
await consumer.close();
await client.close();
})();