我正在尝试在节点 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
ETC
我究竟做错了什么?
编辑:
看起来我没有考虑 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);
}