我使用 Microsoft.Azure.ServiceBus 2.0.0 订阅队列消息,并在使用Encoding.UTF8.GetString(serviceBusMessage.Body)
时获得意外字符。
看起来消息内容应该是有效的XML,但肯定不是。
发送消息的代码使用旧的 WindowsAzure.ServiceBus 4.1.6 库,如下所示:
private void SendToProcessingQueue(Guid accountId, Message msg)
{
string queueName = msg.MessageType.ToLower();
var client = CreateQueueClient(queueName);
client.Send(new BrokeredMessage(new MessageHint()
{
AccountId = accountId,
MessageId = msg.Id,
MessageType = msg.MessageType
}));
}
新旧图书馆是否不兼容?
答案 0 :(得分:0)
是否不兼容 - 在重新实现类库.NET 4.7而不是.NET Standard 2.0并引用 WindowsAzure.ServiceBus 4.1.7 而不是 Microsoft之后,我能够解析消息.Azure.ServiceBus 2.0.0 。 API大致相同,所以我只花了15分钟重新实现。
更新:如果有人知道如何在两个版本之间交换消息,请发布另一个答案,说明应该如何处理。
答案 1 :(得分:0)
要创建兼容的消息,您似乎需要使用DataContractBinarySerializer
对其进行编码。值得庆幸的是,它们在Microsoft.Azure.ServiceBus
nuget包中包含一个。兼容性序列化功能如下所示:
byte[] Serialize<T>(T input)
{
var serializer = Microsoft.Azure.ServiceBus.InteropExtensions.DataContractBinarySerializer<T>.Instance;
MemoryStream memoryStream = new MemoryStream(256);
serializer.WriteObject(memoryStream, input);
memoryStream.Flush();
memoryStream.Position = 0L;
return memoryStream.ToArray();
}
因此,使用新库发送您的消息的方式如下:
private void SendToProcessingQueue(Guid accountId, Message msg)
{
string queueName = msg.MessageType.ToLower();
var client = CreateQueueClient(queueName);
client.Send(new Message(Serialize(new MessageHint()
{
AccountId = accountId,
MessageId = msg.Id,
MessageType = msg.MessageType
})));
}
如果您从旧库中接收到带有新库的消息,则新库的开发人员将提供有用的扩展方法Microsoft.Azure.ServiceBus.InteropExtensions.MessageInteropExtensions.GetBody<T>
来以兼容方式读取消息。您可以这样使用它:
MessageHint hint = message.GetBody<MessageHint>();