标签:
MSMQ可以安装为工作组模式或域模式。如果安装程序没有找到一台运行提供目录服务的消息队列的服务器,则只可以安装为工作组模式,此计算机上的“消息队列”只支持创建专用队列和创建与其他运行“消息队列”的计算机的直接连接。
接下来演示发送数据和接收数据代码的编写方法,下面的示例中使用的是私有的队列类型来演示的操作。首先从发送数据开始,在发送数据时首先要创建我们的MQ,然后根据MQ的地址创建相应的队列,调用队列的send方法将数据信息发送到队列中,如下代码:
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Messaging; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Xml; using System.Xml.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace MsMQTest { class Program { static void Main(string[] args) { //declare the MQ Path string ekQ= ".\\Private$\\EKTestQueue"; //create the MQ if the MQ is not exist if (!MessageQueue.Exists(ekQ)) MessageQueue.Create(ekQ); //create a new queue var queue = new MessageQueue(ekQ); for (int i = 0; i < 2; i++) { //create the model that want to send Test test=new Test(); test.Name = "fdsfd"; test.Sex = "cvx"; //serialize the model string str = Program.xmlSerial(test); //send the model data to queue queue.Send("Test" + str); Console.WriteLine("Message sent {0} \n--------------", "Test" +str); } Console.Read(); // MessageQueue.Delete(ekQ); } public static string xmlSerial<T>(T serializeClass) { string xmlString = string.Empty; XmlWriterSettings settings = new XmlWriterSettings(); XmlSerializer serializer = new XmlSerializer(typeof(T)); StringBuilder xmlStringBuilder = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(xmlStringBuilder)) { serializer.Serialize(writer, serializeClass); xmlString = xmlStringBuilder.ToString(); } return xmlString; } } public class Test { public string Name { get; set; } public string Sex { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Messaging; using System.Text; using System.Threading; namespace MsqueueReaderTest { class Program { static void Main(string[] args) { string ekQ = ".\\Private$\\EKTestQueue"; using (var queue = new MessageQueue(ekQ)) { queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(String) }); var exist = false; while (!MessageQueue.Exists(ekQ)) { Console.WriteLine("No existing queue"); } exist = true; while (exist) { var m = queue.Receive(); Console.WriteLine("Message Received {0} \n--------------",(string)m.Body); // Thread.Sleep(500); } } } } }
标签:
原文地址:http://blog.csdn.net/zhang_xinxiu/article/details/43838397