消息队列用于同步或者异步的高效处理消息队列,它应用的场景包括:
1)关键性的财务数据处理:例如,电子商务。
2)嵌入式和手持程序;
3)户外销售:例如,自动化销售程序;
4)工作流
消息队列不适合客户端和服务器端实时交互的场景,因为队列会出现一定的延迟现象。
MSMQ的实现包括一下几个元素:消息队列、发送器和接受器。消息队列包括公用消息队列、专用消息队列,管理消息队列等。消息队列的发送首先要创建队列,然后才能够发送消息,实例代码如下:
static void SendMessage()
{
try
{
string path = @"FormatName:Direct=TCP:192.168.0.115\private$\killf";
string localPath=@".\private$\killf";
MessageQueue queue;
if (MessageQueue.Exists(localPath))
{
queue = new MessageQueue(path);
}
else
{
queue = MessageQueue.Create(localPath);
}
queue.Formatter = new XmlMessageFormatter(new string[] { "System.String" });
queue.Send("hello world", "message");
Console.WriteLine(queue.FormatName);
Console.ReadKey();
}
catch (Exception ex)
{
throw ex;
}
}
{
try
{
string path = @"FormatName:Direct=TCP:192.168.0.115\private$\killf";
string localPath=@".\private$\killf";
MessageQueue queue;
if (MessageQueue.Exists(localPath))
{
queue = new MessageQueue(path);
}
else
{
queue = MessageQueue.Create(localPath);
}
queue.Formatter = new XmlMessageFormatter(new string[] { "System.String" });
queue.Send("hello world", "message");
Console.WriteLine(queue.FormatName);
Console.ReadKey();
}
catch (Exception ex)
{
throw ex;
}
}
注意:
MessageQueue.Exists 该方法只能够处理本地的路径,不能够处理远程路径,参考链接:
接受消息时,首先获取消息队列,然后根据具体的队列进行操作,操作实例如下:
static void ReceiveMesage()
{
string path = "FormatName:Direct=TCP:192.168.0.115\\private$\\killf";
MessageQueue queue = new MessageQueue(path);
queue.Formatter = new XmlMessageFormatter(new string[] { "System.String" });
while (true)
{
Message message = queue.Receive();
if (message != null)
Console.WriteLine(message.Body.ToString());
}
Console.ReadKey();
}
}
{
string path = "FormatName:Direct=TCP:192.168.0.115\\private$\\killf";
MessageQueue queue = new MessageQueue(path);
queue.Formatter = new XmlMessageFormatter(new string[] { "System.String" });
while (true)
{
Message message = queue.Receive();
if (message != null)
Console.WriteLine(message.Body.ToString());
}
Console.ReadKey();
}
}
另外对于消息队列的处理最好是启动单独的服务和线程,以进行大数据的并发处理。