[英]MSMQ custom message format
我想在MSMQ中發送消息,例如帶有文本的消息
<order><data id="5" color="blue"/></order>
這是標准的XML。 到目前為止,我已經做了Serializable類
[Serializable]
public class order
string id
string color
我正在使用BinaryFormatter。 當我檢查message.BodyStream時,有一些不應該存在的字符(00,01,FF),那么我不會收到此消息而不會出現錯誤。
這個任務似乎很簡單,只需要輸入文字
<order><data id="5" color="blue"/></order>
進入msmq。
挖掘整個重要代碼:
public static void Send()
{
using (message = new Message())
{
request req = new request("1", "blue");
message.Recoverable = true;
message.Body = req.ToString();
message.Formatter = new BinaryMessageFormatter();
using (msmq = new MessageQueue(@".\Private$\testrfid"))
{
msmq.Formatter = new BinaryMessageFormatter();
msmq.Send(message, MessageQueueTransactionType.None);
}
}
}
[Serializable]
public class request
{
private readonly string _order;
private readonly string _color;
public request(string order, string color)
{
_order = order;
_color = color;
}
public request()
{ }
public string Order
{
get { return _order; }
}
public string Color
{
get { return _color; }
}
public override string ToString()
{
return string.Format(@"<request> <job order = ""{0}"" color = ""{1}"" /> </request>",_order,_color);
}
}
您的問題根本不是很清楚。 只要使用BinaryMessageFormatter,就可以向MSMQ發送任何類型的消息。 這是一個例子:
string error = "Some error message I want to log";
using (MessageQueue MQ = new MessageQueue(@".\Private$\Your.Queue.Name"))
{
BinaryMessageFormatter formatter = new BinaryMessageFormatter();
System.Messaging.Message mqMessage = new System.Messaging.Message(error, formatter);
MQ.Send(mqMessage, MessageQueueTransactionType.Single);
MQ.Close();
}
我沒有找到為什么Message.Body在傳遞給Body的字符串之前包含這些ascii字符的原因。 我只是直接填充BodyStream而不是Body,然后讓它自己轉換:
Message.BodyStream = new MemoryStream(Encoding.ASCII.GetBytes(string i want to put as Body))
然后,消息只是字符串而已。
您不需要可序列化的類將字符串發送到消息隊列。
由於您使用的是BinaryMessageFormatter,因此必須首先使用文本編碼器將字符串轉換為字節數組,例如
message.Body = new UTF8Encoding().GetBytes(req.ToString());
我僅以UTF8為例,可以使用任何喜歡的編碼。
然后,當您從隊列中讀取消息時,請記住使用相同的編碼來獲取字符串,例如
string myString = new UTF8Encoding().GetString(message.Body);
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.