1) 为什么?我需要将缓冲区传递给rabbitMQ,发布方法http://www.squaremobius.net/amqp.node/channel_api.html#channel_publish
2)我的数据如下所示
[ // array of objects
{
id: 1,
name: 'John Doe',
prop: {
a: [....], // nested
b: [....],
c: {...}
}
},
...
]
如何正确地将这样的对象数组转换为缓冲区,以便从另一端可以解析回来。
最佳答案
1) Why ?
来自https://www.rabbitmq.com/tutorials/amqp-concepts.html#messages
AMQP messages also have a payload (the data that they carry), which AMQP brokers treat as an opaque byte array. The broker will not inspect or modify the payload. It is possible for messages to contain only attributes and no payload. It is common to use serialisation formats like JSON, Thrift, Protocol Buffers and MessagePack to serialize structured data in order to publish it as the message payload. AMQP peers typically use the "content-type" and "content-encoding" fields to communicate this information, but this is by convention only.
这个版本的 TL;DR 版本是 RabbitMQ 不知道有关您的数据或其格式化/编码方式的任何信息。它将您的消息视为字节数组,要求您处理编码。
amqp.node
库希望您传递一个缓冲区,因为这是 Node.js 处理字节数组之间转换的最简单方法,就像 RabbitMQ 所期望的那样。
How properly convert array of objects like this to buffer, so from the other side could parse back.
在消息生产者中,您需要将消息数据转换为 JSON 字符串(文档),然后 create a buffer由此而来。
var data = [ ... ];
var json = JSON.stringify(data);
var buffer = Buffer.from(json);
在消息使用者方面,您可以执行相反的操作,使用消息body
和turn the buffer into a string ,首先。
var json = message.body.toString();
var data = JSON.parse(json);
此时,您的 data
对象应该是您想要的数据数组,供 Node.js 代码使用。
关于javascript - 将嵌套对象数组转换为 Nodejs Buffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41187889/