?MSMQ功能:实现多服务器应用程序之间消息实时交互。
?使用消息队列首先要在操作系统的添加组件中添加消息队列,在net平台下开发消息队列也比较简单,要专门添加引用system.messageing这个命名空间主要研究MessageQueue这个类。
消息队列分为好几种类型
我们大部分使用的是私有队列,公共队列可能需要安装到工作组管理的机器应该和AD有关的
创建私有队列是这样的?System.Messaging.MessageQueue.Create(".//private$//name");其中。标示机器名字,private标示是私有队列,name是这个队列的名字
公共队列是机器名//队列名,但是一般机器创建的时候会报错
下面是一个简单的类文件,使用了创建,发送和读取的三个基本功能
/// <summary>
///消息队列的简单实例
/// </summary>
public class Msg
{
??? public static string CreateNewQueue(string name)
??? {
??????? if (!System.Messaging.MessageQueue.Exists(".//private$//" + name))//检查是否已经存在同名的消息队列
??????? {
??????????? System.Messaging.MessageQueue mq = System.Messaging.MessageQueue.Create(".//private$//" + name);
??????????? mq.Label = "test";
??????????? return "ok";
??????? }
??????? else
??????? {
??????????? return "已经存在";
??????? }
??? }
??? /// <summary>
??? /// 同步发送消息
??? /// </summary>
??? /// <param name="input">发送的内容</param>
??? /// <param name="queueName">发送哪个消息队列中</param>
??? public static void SendMsg(string input,string queueName)
??? {
?????? // System.Messaging.MessageQueue.Create(".//private$//test2");
??????? System.Messaging.MessageQueue mq = new MessageQueue(".//private$//" + queueName);
??????? System.Messaging.Message message = new System.Messaging.Message();
??????? message.Body = input;
??????? message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) });
??????? mq.Send(message);
??? }
??? /// <summary>
??? /// 同步接收消息
??? /// </summary>
??? /// <param name="queueName">从哪个消息队列接受消息</param>
??? /// <returns></returns>
??? public static string? ReceiveMsg(string queueName)
??? {
??????? System.Messaging.MessageQueue mq = new MessageQueue(".//private$//" + queueName);
??????? if (mq.GetAllMessages().Length == 0)//判断是否还有消息,如果没有消息的话Receive方法会一直独占进程直到有消息为止,所以必须判断
??????? {
??????????? return "没有消息了";
??????? }
??????? else
??????? {
??????????? Message m = mq.Receive();
??????????? m.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) });
??????????? return m.Body.ToString();
??????? }
??? }
}
?
比较简单,代码也很少。更详细的异步读写数据,已经消息队列的更多属性可以查看msnd
?
?
?我所介绍的例子是利用微软的消息队列(msmq)实现多个服务器之间消息实时传递。
应用程序:基于dotnet平台采用WinForm+Webservice开发的应用程序。
每个地区都有自己的数据库和Webservice服务器。
Webservice服务器有很多台,这样多个服务器上用户互相交流就成了问题。思前想后采用了msmq,设计思想如下:
例子:A服务器用户user1发送消息给B服务器上的user2
1、首先是数据库结构是一样的使用sql2005同步用户信息表。2、在每台Webservice服务器上安装msmq。3、当user1发送消息给user2时,判断user2所在服务器,如果user2和发送者不在同一个服务器就使用msmq传递消息给B服务器。4、每个Webservice服务器都有一个消息接收服务程序,用来侦测本服务器消息队列里的消息,反序列化消息内容,写入数据库。5、user2直接读取数据库就可以了。6、实际上就是通过msmq在多个数据库服务器之间消息传递。