ActiveMQ在C#中的應用

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

 

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

 

二、去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,所以下載最新版便可。 windows

 

[c-sharp]  view plain copy
  1. private void StopMonitorThreads()  
  2.         {  
  3.             lock(monitor)  
  4.             {  
  5.                 if(monitorStarted.CompareAndSet(true, false))  
  6.                 {  
  7.                     AutoResetEvent shutdownEvent = new AutoResetEvent(false);  
  8.   
  9.                     // Attempt to wait for the Timers to shutdown, but don't wait  
  10.                     // forever, if they don't shutdown after two seconds, just quit.  
  11.                     this.readCheckTimer.Dispose(shutdownEvent);  
  12.                     shutdownEvent.WaitOne(TimeSpan.FromMilliseconds(2000));  
  13.                     this.writeCheckTimer.Dispose(shutdownEvent);  
  14.                     shutdownEvent.WaitOne(TimeSpan.FromMilliseconds(2000));  
  15.                       
  16.                                                     //WaitOne的定義:public virtual bool WaitOne(TimeSpan timeout,bool exitContext)  
  17.                       
  18.                     this.asyncTasks.Shutdown();  
  19.                     this.asyncTasks = null;  
  20.                     this.asyncWriteTask = null;  
  21.                     this.asyncErrorTask = null;  
  22.                 }  
  23.             }  
  24.         }  

 

三、運行ActiveMQ,找到ActiveMQ解壓後的bin文件夾:.../apache-activemq-5.3.1/bin,執行activemq.bat批處理文件便可啓動ActiveMQ服務器,默認端口爲61616,這可在配置文件中修改。 服務器

 

四、寫C#程序實現ActiveMQ的簡單應用。新建C#工程(一個Producter項目和一個Consumer項目),WinForm或Console程序都可,這裏建的是Console工程,添加對Apache.NMS.dll和Apache.NMS.ActiveMQ.dll的引用,而後便可編寫實現代碼了,簡單的Producer和Consumer實現代碼以下: session

 

producer: async

[c-sharp]  view plain copy
  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.   
  10. namespace Publish  
  11. {  
  12.     class Program  
  13.     {  
  14.         static void Main(string[] args)  
  15.         {  
  16.             try  
  17.             {  
  18.                 //Create the Connection Factory  
  19.                 IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616/");  
  20.                 using (IConnection connection = factory.CreateConnection())  
  21.                 {  
  22.                     //Create the Session  
  23.                     using (ISession session = connection.CreateSession())  
  24.                     {  
  25.                         //Create the Producer for the topic/queue  
  26.                         IMessageProducer prod = session.CreateProducer(  
  27.                             new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("testing"));  
  28.                           
  29.                         //Send Messages  
  30.                         int i = 0;  
  31.   
  32.                         while (!Console.KeyAvailable)  
  33.                         {  
  34.                             ITextMessage msg = prod.CreateTextMessage();  
  35.                             msg.Text = i.ToString();  
  36.                             Console.WriteLine("Sending: " + i.ToString());  
  37.                             prod.Send(msg, Apache.NMS.MsgDeliveryMode.NonPersistent, Apache.NMS.MsgPriority.Normal, TimeSpan.MinValue);  
  38.   
  39.                             System.Threading.Thread.Sleep(5000);  
  40.                             i++;  
  41.                         }  
  42.                     }  
  43.                 }  
  44.   
  45.                 Console.ReadLine();  
  46.            }  
  47.             catch (System.Exception e)  
  48.             {  
  49.                 Console.WriteLine("{0}",e.Message);  
  50.                 Console.ReadLine();  
  51.             }  
  52.         }  
  53.     }  
  54. }  

 

consumer: tcp

[c-sharp]  view plain copy
  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.   
  10. namespace Subscribe  
  11. {  
  12.     class Program  
  13.     {  
  14.         static void Main(string[] args)  
  15.         {  
  16.             try  
  17.             {  
  18.                 //Create the Connection factory  
  19.                 IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616/");  
  20.                   
  21.                 //Create the connection  
  22.                 using (IConnection connection = factory.CreateConnection())  
  23.                 {  
  24.                     connection.ClientId = "testing listener";  
  25.                     connection.Start();  
  26.   
  27.                     //Create the Session  
  28.                     using (ISession session = connection.CreateSession())  
  29.                     {  
  30.                         //Create the Consumer  
  31.                         IMessageConsumer consumer = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("testing"), "testing listener", null, false);  
  32.                           
  33.                         consumer.Listener += new MessageListener(consumer_Listener);  
  34.   
  35.                         Console.ReadLine();  
  36.                     }  
  37.                     connection.Stop();  
  38.                     connection.Close();  
  39.                 }  
  40.             }  
  41.             catch (System.Exception e)  
  42.             {  
  43.                 Console.WriteLine(e.Message);  
  44.             }  
  45.         }  
  46.   
  47.         static void consumer_Listener(IMessage message)  
  48.         {  
  49.             try  
  50.             {  
  51.                 ITextMessage msg = (ITextMessage)message;  
  52.                 Console.WriteLine("Receive: " + msg.Text);  
  53.            }  
  54.             catch (System.Exception e)  
  55.             {  
  56.                 Console.WriteLine(e.Message);  
  57.             }  
  58.         }  
  59.     }  
  60. }  

 

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

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

 

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

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:

[c-sharp]  view plain copy
  1. ITextMessage msg = prod.CreateTextMessage();  
  2.                             msg.Text = i.ToString();  
  3.                             msg.Properties.SetString("myFilter", "test1");  
  4.                             Console.WriteLine("Sending: " + i.ToString());  
  5.                             prod.Send(msg, Apache.NMS.MsgDeliveryMode.NonPersistent, Apache.NMS.MsgPriority.Normal, TimeSpan.MinValue);  

 

consumer:

[c-sharp]  view plain copy
  1. //生成consumer時經過參數設置Selector  
  2. IMessageConsumer consumer = session.CreateConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue("testing"), "myFilter='test1'");  

 

------------------------------------------------------------------------------------------------------------------------------------------------------------

介於許多朋友對Demo程序的需求,上傳一個以前本身寫的WinForm Demo吧,下載地址在這裏:http://download.csdn.net/detail/bodybo/4498147

截圖以下:

MQ發送程序

 

MQ接收程序

相關文章
相關標籤/搜索