探索数据传输新境界:Apache Pulsar的Node.js之旅
const pulsar = require('pulsar-client');
// 创建一个Pulsar客户端实例
const client = new pulsar.Client({
serviceUrl: 'pulsar://localhost:6650',
operationTimeoutSeconds: 5,
});
// 创建一个生产者
async function createProducer() {
const producer = await client.createProducer({
topic: 'persistent://public/default/my-topic',
sendTimeoutMs: 3000,
});
console.log('Producer has been created.');
// 发送消息
await producer.send({
'key': 'message-key',
'data': 'Hello, Pulsar!',
});
console.log('Message has been sent.');
// 关闭生产者
await producer.close();
console.log('Producer has been closed.');
// 关闭客户端
await client.close();
console.log('Client has been closed.');
}
// 异步函数调用
createProducer().catch(err => {
console.error('An error occurred:', err);
});
这段代码展示了如何在Node.js环境中使用Pulsar客户端库创建一个Pulsar生产者,并向指定的topic发送一条消息。代码中使用了async/await来处理异步操作,使得代码更加简洁和易读。
评论已关闭