ActiveMQ application in C,

Source: Internet
Author: User

ActiveMQ application in C,
 

ActiveMQ is a good stuff. Needless to say. ActiveMQ supports multiple languages, such as Java, C, C ++, C #, Ruby, Perl, Python, and PHP. Since I develop a GUI in windows, I am more concerned about C ++ and C #. The ActiveMQ of C # is very simple, and Apache provides NMS (.. Net Messaging Service. net development, you only need to perform the following steps to establish a simple implementation. C ++ applications are relatively troublesome. I will write an article later.

1. download the latest ActiveMQ version from the ActiveMQ official website at http://activemq.apache.org/download.html. I used to describe 5.3.1 and 5.3.2 now.

2. Go to the ActiveMQ official website to download the latest Apache. NMS version. Please note that if you download NMS of version 1.2.0. activeMQ, Apache. NMS. activeMQ. dll has a bug in actual use, that is, when the ActiveMQ application is stopped, the WaitOne function exception will be thrown. Check the source code in the src package and find that it is caused by Apache. NMS. activeMQ-1.2.0-src \ src \ main \ csharp \ Transport \ InactivityMonitor. the following code in cs can be modified to recompile the source code. Check that the latest version 1.3.0 has fixed this bug, So download the latest version.

 

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 // definition of 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 // definition of 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. Run ActiveMQ and find the bin folder after ActiveMQ is decompressed :... \ apache-activemq-5.3.1 \ bin, execute activemq. the ActiveMQ server can be started in the bat batch file. The default port is 61616, which can be modified in the configuration file.

4. Write a C # program to implement simple ActiveMQ applications. Create a C # project (a Producter project and a Consumer project), and use either the WinForm or Console program. The Console project is created here and added to Apache. NMS. dll and Apache. NMS. activeMQ. dll reference, and then you can write the implementation code. The simple Producer and Consumer implementation code is as follows:

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 }  

 

Function implemented by the Program: The producer creates a topic named testing and sends messages to the topic every five seconds. consumer subscribes to the topic testing, therefore, as long as the producer sends the testing topic message to the ActiveMQ server, the server sends the message to the consumer that subscribes to the testing topic.

Compile and generate producer.exeand consumer.exe, and execute two exe to view the message sending and receiving.

In this example, the Topic is created. ActiveMQ also supports another method: Queue, P2P. What is the difference between the two? The difference is that a Topic is broadcast, that is, if a Topic is subscribed by multiple consumers, the server sends the message to all consumers as long as a message arrives at the server, while the Queue is point-to-point, that is, a message can only be sent to one consumer. If a Queue is subscribed by multiple consumers, messages are sent to different consumers in turn in no special case. For example:

Msg1 --> consumer

Msg2 --> consumer B

Msg3 --> consumer C

Msg4 --> consumer

Msg5 --> consumer B

Msg6 --> consumer C

In special cases, ActiveMQ supports the filtering mechanism, that is, the producer can set the message Properties. This attribute corresponds to the consumer Selector, and only the selector set by the consumer matches the message Properties, the message is sent to the consumer. Both Topic and Queue support Selector.

How to Set Properties and Selector? See the following code:

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 // set Selector 4 IMessageConsumer consumer = session through parameters when generating a consumer. createConsumer (new Apache. NMS. activeMQ. commands. activeMQQueue ("testing"), "myFilter = 'test1'"); 5 // set Selector 6 IMessageConsumer consumer = session through parameters when generating a consumer. createConsumer (new Apache. NMS. activeMQ. commands. activeMQQueue ("testing"), "myFilter = 'test1'"); 7}

This article from blog: http://www.cnblogs.com/guthing/archive/2010/06/17/1759333.html

Thanks to guthing

ActiveMQ other articles recommended: http://blog.csdn.net/lee353086/article/details/6819123

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.