static readonly string mqname=@".\Private$\MSMQ1"; if (!MessageQueue.Exists(mqname))//判断私有消息是否存在 { MessageQueue.Create(mqname, false); } private void CreateThread() { t = new Thread(() => { while (true) { var mq = new MessageQueue(mqname); System.Messaging.Message message = new System.Messaging.Message(); //为了避免存放消息队列的计算机重新启动而丢失消息,可以通过设置消息对象的Recoverable属性为true, //在消息传递过程中将消息保存到磁盘上来保证消息的传递,默认为false。 //message.Recoverable = true; message.Body = new Apple { Name = DateTime.Now.ToString(), Price = r.Next() * 100 }; message.Formatter = new XmlMessageFormatter(new Type[] { typeof(Apple) }); mq.Send(message); Thread.Sleep(1000); } }); t.IsBackground = true; }
static readonly string mqname = @"FormatName:Direct=TCP:192.168.0.21\Private$\MSMQ1"; static ManualResetEvent signal = new ManualResetEvent(false); //static int count = 0; static void Main(string[] args) { var mq = new MessageQueue(mqname); mq.Formatter= new XmlMessageFormatter(new Type[] { typeof(Apple) }); // Add an event handler for the ReceiveCompleted event. mq.ReceiveCompleted +=new ReceiveCompletedEventHandler(MyReceiveCompleted); mq.BeginReceive(); //mq.PeekCompleted += Mq_PeekCompleted; //mq.BeginPeek(); //signal.WaitOne(); Console.ReadKey(); } private static void Mq_PeekCompleted(object sender, PeekCompletedEventArgs e) { try { // Connect to the queue. MessageQueue mq = (MessageQueue)sender; Message m = mq.EndPeek(e.AsyncResult); Apple a = (Apple)m.Body; Console.WriteLine(a.Price.ToString() + "\t" + a.Name); mq.BeginPeek(); } catch (MessageQueueException) { } } private static void MyReceiveCompleted(object sender, ReceiveCompletedEventArgs e) { try { MessageQueue mq = (MessageQueue)sender; Message m = mq.EndReceive(e.AsyncResult); Apple a = (Apple)m.Body; Console.WriteLine(a.Price.ToString()+"\t"+a.Name); mq.BeginReceive(); } catch (MessageQueueException) { } }
msdn手册:https://msdn.microsoft.com/zh-cn/library/system.messaging.messagequeue.beginpeek(v=vs.80).aspx
MSMQ 跨服务器读写队列的“消息队列系统的访问被拒绝”的解决方案:
服务器上消息队列权限设置:给ANONYMOUS LOGON赋予所有权限;
修改服务器的注册表,允许非验证客户端访问
注册表新增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
peek和receive的区别:receive后消息队列清空;peek不清空。