Node.js 如何在节点js中为kafka主题编写jsonArray
如何将数组(包含json字符串)写入节点js中的Kakfa主题Node.js 如何在节点js中为kafka主题编写jsonArray,node.js,arrays,json,apache-kafka,Node.js,Arrays,Json,Apache Kafka,如何将数组(包含json字符串)写入节点js中的Kakfa主题 server.on('package:publish', async event => { try { const responses = await producer.send({ topic: process.env.TOPIC, messages: [{ // Name of the published package as key, to make sure that
server.on('package:publish', async event => {
try {
const responses = await producer.send({
topic: process.env.TOPIC,
messages: [{
// Name of the published package as key, to make sure that we process events in order
key: event.name,
// The message value is just bytes to Kafka, so we need to serialize our JavaScript
// object to a JSON string. Other serialization methods like Avro are available.
value: JSON.stringify(array)
}]
})
console.log('Published message', { responses })
} catch (error) {
console.error('Error publishing message', error)
}
})
消息值只是Kafka的字节数,因此我们需要序列化JavaScript
对象转换为JSON字符串。其他序列化方法(如Avro)也可用
只需将数组数据包装为JSON.stringify(array),并以值形式发送,
在消费端,您可以使用JSON.parse(message.value)
这里有一些帮助链接