百宝箱演示WCF消息队列解决方案

消息就是信息的来源,在WCF中消息队列分为公共队列、专用队列、管理队列、响应队列四种,下面我们就简单的分析一下WCF消息队列吧。MessageQueue.Create参数是存放消息队列的位置.这个基本就完成了创建和发送消息的主程序.下面我们来建立一个客户端,来访问消息队列,获取消息,同样建立一个控制台应用程序,添加引用和代码:

 
 
  1. 1namespace MSMQClient  
  2. class Program  
  3. {  
  4. static void Main(string[] args)  
  5. {  
  6. //Get public queue message  
  7. if (MessageQueue.Exists(@".FrankMSMQ"))//判断是否存在消息队列  
  8. {  
  9.  
  10. using(MessageQueue mq = new MessageQueue(@".FrankMSMQ"))//创建消息队列对象  
  11. {  
  12. mq.Formatter = new XmlMessageFormatter(new string[] { "System.String" });//设置消息队列的格式化器  
  13. //mq.Send("Sample Message", ":Label");  
  14. Message msg = mq.Receive();//从队列接受消息  
  15. Console.WriteLine("Received MSMQ Message is :{0}", msg.Body);//输出消息  
  16. }  
  17. //Console.Read();  
  18. }  
  19. //Get private queue message  
  20. if (MessageQueue.Exists(@".Private$FrankMSMQ"))//判断私有消息是否存在  
  21. {  
  22. using (MessageQueue mq = new MessageQueue(@".Private$FrankMSMQ"))  
  23. {  
  24. mq.Formatter = new XmlMessageFormatter(new string[] { "System.String" });//设置消息队列格式化器  
  25. //mq.Send("Sample Message", ":Label");  
  26. Message msg = mq.Receive();//接收消息  
  27. Console.WriteLine("Received MSMQ Private Message is: {0}", msg.Body);//输出消息  
  28. }  
  29. }  
  30. Console.Read();  
  31. }  
  32. }  
  33. }  

#T#消息接收同样需要实例化一个WCF消息队列对象, using(MessageQueue mq = new MessageQueue(@".FrankMSMQ"))负责创建WCF消息队列对象.其次 mq.Formatter = new XmlMessageFormatter(new string[] { "System.String" })这行代码负责设置消息队列的格式化器,因为消息的传递过程中存在格式化的问题.我们接收消息的时候必须指定消息队列的格式化属性Formatter, 队列才能接受消息。

XmlMessageFormatter的作用是进行消息的XML串行化.BinaryMessageFormatter则把消息格式化为二进制数据进行传输.ActiveXMessageFormatter把消息同样进行二进制格式化,区别是可以使用COM读取队列中的消息.当然消息队列还可以发送复杂的对象,前提是这个对象要可串行化,具体的格式取决与队列的格式化器设置.此外消息队列还支持事务队列来确保消息只发送一次和发送的顺序.最近在研究SOA,所以系统系统学习一下WCF及其相关的技术,以上就是这个消息队列的基本的概念和简单的编程实现.下一节是关于.Net Remoting的基础知识和开发的文章.~

THE END