前言
MQ——Message Queue,中文翻译为“消息队列”,维基百科上的这样描述:
消息队列(英语:Message queue)是一种进程间通信或同一进程的不同线程间的通信方式,软件的贮列用来处理一系列的输入,通常是来自使用者。消息队列提供了异步的通信协议,每一个贮列中的纪录包含详细说明的资料,包含发生的时间,输入装置的种类,以及特定的输入参数,也就是说:消息的发送者和接收者不需要同时与消息队列互交。消息会保存在队列中,直到接收者取回它。
实际应用中有多种MQ,包括MSMQ,Active MQ,Jboss MQ等.本文简单介绍.net环境下Active MQ入门。
准备工作
1.下载Active MQ,地址:http://activemq.apache.org/download.html(我下的是ActiveMQ 5.7.0 Release),下载完成后解压缩即可。ActiveMQ是一个开源的JMS服务器;
2.下载NMS,地址:http://activemq.apache.org/nms/download.html。网站提供源码下载,可以根据需要编译成指定.net framework版本。如果下载的是release版本,直接将具体.net版本目录下Apache.NMS.ActiveMQ.dll和Apache.NMS.dll拷贝出来。
Hello ActiveMQ
1.新建空解决方案:HelloActiveMQ.sln
2.在当前解决方案中分别新建两个控制台程序:ConsoleCustomer.csproj(消费者)和ConsoleProcucer.csproj(生产者)。生产者将消息发送给ActiveMQ,然后ActiveMQ将消息推送给符合条件的消费者;
3.在ConsoleCustomer.csproj(消费者)和ConsoleProcucer.csproj(生产者)两个项目中均添加对Apache.NMS.ActiveMQ.dll和Apache.NMS.dll的引用;
4.在ConsoleProcucer项目的program.cs中添加如下代码(代码中已经又注释):
1 class Program
2 {
3 static IConnectionFactory _factory = null;
4 static IConnection _connection = null;
5 static ITextMessage _message = null;
6
7 static void Main(string[] args)
8 {
9 //创建工厂
10 _factory = new ConnectionFactory("tcp://localhost:61616/");
11
12 try
13 {
14 //创建连接
15 using (_connection = _factory.CreateConnection())
16 {
17 //创建会话
18 using (ISession session = _connection.CreateSession())
19 {
20 //创建一个主题
21 IDestination destination = new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("topic");
22
23 //创建生产者
24 IMessageProducer producer = session.CreateProducer(destination);
25
26 Console.WriteLine("Please enter any key to continue! ");
27 Console.ReadKey();
28 Console.WriteLine("Sending: ");
29
30 //创建一个文本消息
31 _message = producer.CreateTextMessage("Hello AcitveMQ....");
32
33 //发送消息
34 producer.Send(_message, MsgDeliveryMode.NonPersistent, MsgPriority.Normal, TimeSpan.MinValue);
35 }
36 }
37
38 }
39 catch (Exception ex)
40 {
41 Console.WriteLine(ex.ToString());
42 }
43
44 Console.ReadLine();
45
46 }
47 }
5.在ConsoleCustomer项目的program.cs中添加如下代码:
1 class Program
2 {
3 static IConnectionFactory _factory = null;
4
5 static void Main(string[] args)
6 {
7 try
8 {
9 //创建连接工厂
10 _factory = new ConnectionFactory("tcp://localhost:61616/");
11 //创建连接
12 using (IConnection conn = _factory.CreateConnection())
13 {
14 //设置客户端ID
15 conn.ClientId = "Customer";
16 conn.Start();
17 //创建会话
18 using (ISession session = conn.CreateSession())
19 {
20 //创建主题
21 var topic = new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("topic");
22
23 //创建消费者
24 IMessageConsumer consumer = session.CreateDurableConsumer(topic, "Customer", null, false);
25
26 //注册监听事件
27 consumer.Listener += new MessageListener(consumer_Listener);
28
29 //这句代码非常重要,
30 //这里没有read方法,Session会话会被关闭,那么消费者将监听不到生产者的消息
31 Console.Read();
32 }
33
34 //关闭连接
35 conn.Stop();
36 conn.Close();
37 }
38
39 }
40 catch (Exception ex)
41 {
42 Console.Write(ex.ToString());
43 }
44
45 }
46
47 /// <summary>
48 /// 消费监听事件
49 /// </summary>
50 /// <param name="message"></param>
51 static void consumer_Listener(IMessage message)
52 {
53 ITextMessage msg = (ITextMessage)message;
54 Console.WriteLine("Receive: " + msg.Text);
55 }
上述代码生成成功后,一个ActiveMQ的入门程序已经完成,接下来便是测试了。
测试
1.启动之前解压过的ActiveMQ程序,在apache-activemq-5.7.0\bin目录下运行activemq.bat批处理文件。运行截图如下:
2.分别运行之前生成的ConsoleProcucer.exe.和ConsoleCustomer.exe,在ConsoleProcucer.exe中根据提示输入任意键。我们便可以检测ConsoleCustomer.exe有没有接收到我们发送的“Hello ActiveMQ”文本。结果如下:
ConsoleProcucer.exe截图
ConsoleCustomer.exe截图
通过验证我们发现通过ActiveMQ发送消息成功。
总结:
1.ConnectionFactory 是连接工厂,负责创建Connection,Connection 负责创建 Session,Session 创建 MessageProducer(用来发消息) 和 MessageConsumer(用来接收消息),Destination 是消息的目的地;
2.Connection一定要调用Start(),才能接收消息。关闭Connection时先调用Stop(),然后再调用Close();
3.Session在接收消息之前不能关闭,否则监听不到消息;
4.Connection,Session不使用时应该及时关闭,避免内存泄露;
5.ActiveMQ支持topic(主题,广播消息)和Queue(队列,点对点消息)。
注:源码中另外提供了winform实现。需要注意的是winform中消息监听事件在接受到消息后,由于当前不是处于UI线程,是不能直接操作Winform UI的,需要使用Invoke,详情请参照源码。