消息队列的使用
发送消息:
代码步骤:1,准备路径
2,实例化MessageQueue对象
3,发送消息Send();
private static void SendQueue(string body) { string MSmqPath = @".\private$\myQueue"; try { MessageQueue _messageQueue = MessageQueue.Exists(MSmqPath) ? new MessageQueue(MSmqPath) : MessageQueue.Create(MSmqPath); _messageQueue.Formatter = new XmlMessageFormatter(new[] { typeof(string) }); Message myMessage = new Message(); myMessage.Body = body; _messageQueue.Send(myMessage); } catch (Exception exception) { Console.WriteLine(exception); } }
注意事项:1,路径
如果是远程发送消息,必须这样写
MSmqPath = @"FormatName:Direct=TCP:132.232.61.60\Private$\myQueue";
MessageQueue _messageQueue = new MessageQueue(MSmqPath);
队列是否存在的方法,和创建,都是不支持远程机器的,这个看一下MSDN的帮助就知道了!直接new出来吧
接受消息:
private static void LoadAccessMessQueue() { try { string MSmqPath=@".\private$\myQueue"; _messageQueue = MessageQueue.Exists(MSmqPath) ? new MessageQueue(MSmqPath) : MessageQueue.Create(MSmqPath); _messageQueue.Formatter = new XmlMessageFormatter(new[] { typeof(string) }); _messageQueue.ReceiveCompleted += OnReceiveCompleted;//当消息接受完成时被调用 Message[] array = _messageQueue.GetAllMessages(); _messageQueue.BeginReceive(); } catch (Exception exception) { Console.WriteLine(exception); } } private static void OnReceiveCompleted(object sender, ReceiveCompletedEventArgs e) { var queue = (MessageQueue)sender; try { queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); //停止接受信息 Message message = queue.EndReceive(e.AsyncResult); Console.WriteLine(message.Body.ToString()); } catch (Exception exception) { Console.WriteLine(exception); } finally { queue.BeginReceive(); } }
注意事项:1,本地读取服务端消息队列时,服务器的权限需要设置
-
-
- 服务器上消息队列权限设置:给every one赋予所有权限;
- 修改服务器的注册表,允许非验证客户端访问
- 注册表新增HKLM\Software\Microsoft\MSMQ\Parameters\security\AllowNonauthenticatedRpc项,设置其DWORD值为1
- 注册表新增HKLM\Software\Microsoft\MSMQ\Parameters\security\NewRemoteReadServerDenyWorkgroupClient项,设置其DWORD值为1
MSMQ的安全访问控制说明参见:http://msdn.microsoft.com/en-us/library/4108f68e-80f5-40e1-b3df-b713cc4dff79(prot.20).aspx
- 服务器上消息队列权限设置:给every one赋予所有权限;
-
为什么使用消息队列?