MSMQ 和 ProtoBuf-Net 序列化 c# [英] MSMQ and ProtoBuf-Net serialization c#
问题描述
我有一个具有许多属性的类,其中之一是 byte[] 属性.我想使用 MSMQ 将此类发送到另一台服务器.但在发送之前,我想使用 ProtoBuf-Net 对其进行序列化.是否可以将 ProtoBuf-Net 序列化程序附加到 MSMQ?
I have a class with many properties, one of them are byte[] property. I would like to send this class to another server using MSMQ. But before sending it I would like to serialize it using ProtoBuf-Net. Is it possible to attach ProtoBuf-Net serializer to MSMQ?
坦率地说,我不明白如何将课程发送到队列.我尝试使用下面的代码将类放入 MSMQ 队列,但出现异常生成 XML 文档时出错."
Frankly speaking I do not understand how to send class to queue. I have tried to use code below to put class to MSMQ queue but got exception "There was an error generating the XML document."
EntityBase 是我想发送的一个类.以前我使用我自己的基于文件系统的消息系统和 ProtoBuf-Net 来序列化类.
EntityBase is a class which I would like to send. Previously I have used my own File System based messaging system and ProtoBuf-Net to serialize class.
const string queueName = @".\private$\TestQueue";
private static void SendMessageToQueue(EntityBase entity)
{
// check if queue exists, if not create it
MessageQueue msMq = null;
if (!MessageQueue.Exists(queueName))
{
msMq = MessageQueue.Create(queueName);
}
else
{
msMq = new MessageQueue(queueName);
}
try
{
msMq.Send(entity);
}
catch (MessageQueueException ee)
{
Console.Write(ee.ToString());
}
catch (Exception eee)
{
Console.Write(eee.ToString());
}
finally
{
msMq.Close();
}
Console.WriteLine("Message sent ......");
}
推荐答案
我的建议是:发送一个 string
或一个 byte[]
作为消息;你可以这样做:
My advice would be: send either a string
or a byte[]
as the message; you can do this as:
byte[] body;
using(var ms = new MemoryStream()) {
Serializer.Serialize(ms, entity);
body = ms.ToArray();
}
然后Send(body)
,或者如果你想要一个string
,然后Send(Convert.ToBase64String(body))
.并将其反转为另一端.
and then Send(body)
, or if you want a string
, then Send(Convert.ToBase64String(body))
. And reverse this as the other end.
看起来还有一种机制可以将 Message
与 IMessageFormatter
一起传递,但我不确定它是否值得.阅读示例:
There looks to also be a mechanism for passing a Message
along with an IMessageFormatter
, but I'm not sure it is worth it. Example of reading:
Message msg = // receive
byte[] body = (byte[])msg.Body;
EntityBase entity;
using(var ms = new MemoryStream(body)) {
entity = Serializer.Deserialize<EntityBase>(ms);
}
或(如果选择传递string
):
string base64 = (string)msg.Body;
byte[] body = Convert.FromBase64String(base64);
// as before
这篇关于MSMQ 和 ProtoBuf-Net 序列化 c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!