ActiveMQ在C#中的應用


  本文是在.NET Framework框架下的應用,截止到目前ActiveMQ還不支持.NET Core,而RabbitMQ已經支持.NET Core,希望ActiveMQ能盡快支持。

ActiveMQ是個好東東,不必多說。ActiveMQ提供多種語言支持,如Java, C, C++, C#, Ruby, Perl, Python, PHP等。由於我在windows下開發GUI,比較關心C++和C#,其中C#的ActiveMQ很簡單,Apache提供NMS(.Net Messaging Service)支持.Net開發,只需如下幾個步驟即能建立簡單的實現。C++的應用相對麻煩些,稍后寫文章介紹。

1、去ActiveMQ官方網站下載最新版的ActiveMQ,網址:http://activemq.apache.org/download.html。我之前下的是5.3.1,5.3.2現在也已經出來了。

2、去ActiveMQ官方網站下載最新版的Apache.NMS,網址:http://activemq.apache.org/nms/download.html,需要下載Apache.NMS和Apache.NMS.ActiveMQ兩個bin包,如果對源碼感興趣,也可下載src包。這里要提醒一下,如果下載1.2.0版本的NMS.ActiveMQ,Apache.NMS.ActiveMQ.dll在實際使用中有個bug,即停止ActiveMQ應用時會拋WaitOne函數異常,查看src包中的源碼發現是由於Apache.NMS.ActiveMQ-1.2.0-src\src\main\csharp\Transport\InactivityMonitor.cs中的如下代碼造成的,修改一下源碼重新編譯即可。看了一下最新版1.3.0已經修復了這個bug,因此下載最新版即可。

 

 1      private void StopMonitorThreads()   
 2         {   
 3             lock(monitor)   
 4             {   
 5                 if(monitorStarted.CompareAndSet(true, false))   
 6                 {   
 7                     AutoResetEvent shutdownEvent = new AutoResetEvent(false);   
 8                     // Attempt to wait for the Timers to shutdown, but don't wait   
 9                     // forever, if they don't shutdown after two seconds, just quit.   
10                     this.readCheckTimer.Dispose(shutdownEvent);   
11                     shutdownEvent.WaitOne(TimeSpan.FromMilliseconds(2000));   
12                     this.writeCheckTimer.Dispose(shutdownEvent);   
13                     shutdownEvent.WaitOne(TimeSpan.FromMilliseconds(2000));   
14                                                     //WaitOne的定義:public virtual bool WaitOne(TimeSpan timeout,bool exitContext)   
15                     this.asyncTasks.Shutdown();   
16                     this.asyncTasks = null;   
17                     this.asyncWriteTask = null;   
18                     this.asyncErrorTask = null;   
19                 }   
20             }   
21         }  
22      private void StopMonitorThreads() 23 { 24 lock(monitor) 25 { 26 if(monitorStarted.CompareAndSet(true, false)) 27 { 28 AutoResetEvent shutdownEvent = new AutoResetEvent(false); 29 30 // Attempt to wait for the Timers to shutdown, but don't wait 31 // forever, if they don't shutdown after two seconds, just quit. 32 this.readCheckTimer.Dispose(shutdownEvent); 33 shutdownEvent.WaitOne(TimeSpan.FromMilliseconds(2000)); 34 this.writeCheckTimer.Dispose(shutdownEvent); 35 shutdownEvent.WaitOne(TimeSpan.FromMilliseconds(2000)); 36 //WaitOne的定義:public virtual bool WaitOne(TimeSpan timeout,bool exitContext) 37 this.asyncTasks.Shutdown(); 38 this.asyncTasks = null; 39 this.asyncWriteTask = null; 40 this.asyncErrorTask = null; 41 } 42 } 43 }

 

3、運行ActiveMQ,找到ActiveMQ解壓后的bin文件夾:...\apache-activemq-5.3.1\bin,執行activemq.bat批處理文件即可啟動ActiveMQ服務器,默認端口為61616,這可在配置文件中修改。

4、寫C#程序實現ActiveMQ的簡單應用。新建C#工程(一個Producter項目和一個Consumer項目),WinForm或Console程序均可,這里建的是Console工程,添加對Apache.NMS.dll和Apache.NMS.ActiveMQ.dll的引用,然后即可編寫實現代碼了,簡單的Producer和Consumer實現代碼如下:

producer:

 1 using System;   
 2 using System.Collections.Generic;   
 3 using System.Text;   
 4 using Apache.NMS;   
 5 using Apache.NMS.ActiveMQ;   
 6 using System.IO;   
 7 using System.Xml.Serialization;   
 8 using System.Runtime.Serialization.Formatters.Binary;   
 9 namespace Publish   
10 {   
11     class Program   
12     {   
13         static void Main(string[] args)   
14         {   
15             try  
16             {   
17                 //Create the Connection Factory   
18                 IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616/");   
19                 using (IConnection connection = factory.CreateConnection())   
20                 {   
21                     //Create the Session   
22                     using (ISession session = connection.CreateSession())   
23                     {   
24                         //Create the Producer for the topic/queue   
25                         IMessageProducer prod = session.CreateProducer(   
26                             new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("testing"));   
27                         //Send Messages   
28                         int i = 0;   
29                         while (!Console.KeyAvailable)   
30                         {   
31                             ITextMessage msg = prod.CreateTextMessage();   
32                             msg.Text = i.ToString();   
33                             Console.WriteLine("Sending: " + i.ToString());   
34                             prod.Send(msg, Apache.NMS.MsgDeliveryMode.NonPersistent, Apache.NMS.MsgPriority.Normal, TimeSpan.MinValue);   
35                             System.Threading.Thread.Sleep(5000);   
36                             i++;   
37                         }   
38                     }   
39                 }   
40                 Console.ReadLine();   
41            }   
42             catch (System.Exception e)   
43             {   
44                 Console.WriteLine("{0}",e.Message);   
45                 Console.ReadLine();   
46             }   
47         }   
48     }   
49 } 

consumer:

 

 1 using System;   
 2 using System.Collections.Generic;   
 3 using System.Text;   
 4 using Apache.NMS;   
 5 using Apache.NMS.ActiveMQ;   
 6 using System.IO;   
 7 using System.Xml.Serialization;   
 8 using System.Runtime.Serialization.Formatters.Binary;   
 9 namespace Subscribe   
10 {   
11     class Program   
12     {   
13         static void Main(string[] args)   
14         {   
15             try  
16             {   
17                 //Create the Connection factory   
18                 IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616/");   
19                 //Create the connection   
20                 using (IConnection connection = factory.CreateConnection())   
21                 {   
22                     connection.ClientId = "testing listener";   
23                     connection.Start();   
24                     //Create the Session   
25                     using (ISession session = connection.CreateSession())   
26                     {   
27                         //Create the Consumer   
28                         IMessageConsumer consumer = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("testing"), "testing listener", null, false);   
29                         consumer.Listener += new MessageListener(consumer_Listener);   
30                         Console.ReadLine();   
31                     }   
32                     connection.Stop();   
33                     connection.Close();   
34                 }   
35             }   
36             catch (System.Exception e)   
37             {   
38                 Console.WriteLine(e.Message);   
39             }   
40         }   
41         static void consumer_Listener(IMessage message)   
42         {   
43             try  
44             {   
45                 ITextMessage msg = (ITextMessage)message;   
46                 Console.WriteLine("Receive: " + msg.Text);   
47            }   
48             catch (System.Exception e)   
49             {   
50                 Console.WriteLine(e.Message);   
51             }   
52         }   
53     }   
54 }  

 

程序實現的功能:生產者producer建立名為testing的主題,並每隔5秒向該主題發送消息,消費者consumer訂閱了testing主題,因此只要生產者發送testing主題的消息到ActiveMQ服務器,服務器就將該消息發送給訂閱了testing主題的消費者。

編譯生成producer.exe和consumer.exe,並執行兩個exe,即可看到消息的發送與接收了。

這個例子是建的主題(Topic),ActiveMQ還支持另一種方式:Queue,即P2P,兩者有什么區別呢?區別在於,Topic是廣播,即如果某個Topic被多個消費者訂閱,那么只要有消息到達服務器,服務器就將該消息發給全部的消費者;而Queue是點到點,即一個消息只能發給一個消費者,如果某個Queue被多個消費者訂閱,沒有特殊情況的話消息會一個一個地輪流發給不同的消費者,比如:

msg1-->consumer A

msg2-->consumer B

msg3-->consumer C

msg4-->consumer A

msg5-->consumer B

msg6-->consumer C

特殊情況是指:ActiveMQ支持過濾機制,即生產者可以設置消息的屬性(Properties),該屬性與消費者端的Selector對應,只有消費者設置的selector與消息的Properties匹配,消息才會發給該消費者。Topic和Queue都支持Selector。

Properties和Selector該如何設置呢?請看如下代碼:

producer:

 1 public void SetProperties()
 2 {
 3 ITextMessage msg = prod.CreateTextMessage();   
 4                             msg.Text = i.ToString();   
 5                             msg.Properties.SetString("myFilter", "test1");   
 6                             Console.WriteLine("Sending: " + i.ToString());   
 7                             prod.Send(msg, Apache.NMS.MsgDeliveryMode.NonPersistent, Apache.NMS.MsgPriority.Normal, TimeSpan.MinValue);  
 8 ITextMessage msg = prod.CreateTextMessage(); 
 9                             msg.Text = i.ToString(); 
10                             msg.Properties.SetString("myFilter", "test1"); 
11                             Console.WriteLine("Sending: " + i.ToString()); 
12                             prod.Send(msg, Apache.NMS.MsgDeliveryMode.NonPersistent, Apache.NMS.MsgPriority.Normal, TimeSpan.MinValue);
13 
14 }

consumer:

1 public void SetSelector()
2 {
3 //生成consumer時通過參數設置Selector   
4 IMessageConsumer consumer = session.CreateConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue("testing"), "myFilter='test1'");  
5 //生成consumer時通過參數設置Selector 
6 IMessageConsumer consumer = session.CreateConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue("testing"), "myFilter='test1'");
7 }

 

該文章來自博客園:http://www.cnblogs.com/guthing/archive/2010/06/17/1759333.html 

經過簡單的整理,感謝guthing

ActiveMQ 其他文章推薦:http://blog.csdn.net/lee353086/article/details/6819123


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM