【发布时间】:2020-10-12 05:46:51
【问题描述】:
我正在尝试在节点 js 上使用来自 RMQ 的 protobuf 消息。 protobuf 消息是使用 C#.Net 上的 protobuf-net 创建的
例如,c# 对象如下所示:
[ProtoContract]
public class PositionOpenNotification : MessageBase
{
[ProtoMember(1)]
public int PositionID { get; set; }
[ProtoMember(2)]
public int InstrumentID { get; set; }
..
..Down to tag 30
然后将其添加到 RMQ,我们在另一端使用具有相同对象的 .net 侦听器对其进行解码。
但是现在我们想从 nodejs 读取消息。 为此,我在 nodejs 端使用 amqplib 和 protobuf-js。
我试图使用带有如下装饰器的对象来解码消息:
import { Message, Type, Field } from "protobufjs/light";
@Type.d("PositionOpenNotification")
export class PositionOpenNotification extends Message<PositionOpenNotification> {
@Field.d(1,"int32", "required")
public PositionID: number;
}
然后像这样解码:
ch.consume(q.queue, function(msg, res) {
try {
if(msg.content) {
let decoded = PositionOpenNotification.decode( msg.content);
console.log(" Received %s", decoded,q.queue);
}
} catch (e) {
console.log("Error %s ", e.message)
}
}
其中 ch 是 amqplib RMQ 通道。
但我总是遇到以下错误之一:
偏移 2 处的线类型 7 无效
偏移 2 处的线类型 4 无效
偏移 2 处的线类型 6 无效
索引超出范围:237 + 10 > 237
等
我做错了什么?
编辑:
看起来我没有考虑到 MessageBase(PositionOpenNotification 继承的抽象)也是一个 ProtoContract 并且数据以长度前缀序列化的事实。
所以最后这是有效的:
添加一个带有 PositionOpenNotification 对象的 MessageBase 对象:
@Type.d("MessageBase")
export class MessageBase extends Message<MessageBase> {
@Field.d(108, PositionOpenNotification)
public positionOpenNotification: PositionOpenNotification;
}
然后在反序列化时:
if(msg.content) {
var reader = Reader.create(msg.content);
let decoded = MessageBase.decodeDelimited(reader);
}
【问题讨论】:
标签: node.js protocol-buffers protobuf-net protobuf.js node-amqplib