ACTIVEMQ in C # application example Analysis _c# tutorial

Source: Internet
Author: User
Tags readline serialization

The example of this article describes the application of ACTIVEMQ in C #. Share to everyone for your reference, specific as follows:

ACTIVEMQ is a good thing, needless to say. ACTIVEMQ offers multiple language support, such as Java, C, C + +, C #, Ruby, Perl, Python, PHP, and so on. Since I developed the GUI under Windows, I am more concerned with C + + and C #, where C # ACTIVEMQ is very simple, Apache provides NMS (. NET messaging Service) to support. NET development, just a few steps to build a simple implementation. C + + application is relatively troublesome, later will an article introduction.

1, to ACTIVEMQ official website Download the latest version of ACTIVEMQ, Web site: http://activemq.apache.org/download.html. I was 5.3.1,5.3.2 before, and now I'm out.

2, to ACTIVEMQ official website Download the latest version of APACHE.NMS, Web site: http://activemq.apache.org/nms/ Download.html, you need to download Apache.nms and Apache.NMS.ActiveMQ Two bin packages, if you are interested in the source code, you can download the SRC package. Here, to remind you, If download 1.2.0 version of Nms.activemq,apache.nms.activemq.dll in the actual use of a bug, that is, stop ActiveMQ application will throw WaitOne function exception, see the SRC package source found is due to Apache.NMS.ActiveM Q-1.2.0-src\src\main\csharp\transport\inactivitymonitor.cs in the following code caused, modify the source to recompile. Look at the latest version of 1.3.0 has fixed the bug, so download the latest version can be.

private void Stopmonitorthreads ()
{
  Lock (monitor)
  {
    if (Monitorstarted.compareandset (True, false))
    {
      AutoResetEvent shutdownevent = new AutoResetEvent (false);
      Attempt to the "timers to shutdown", but don ' t wait
      //forever, if they don ' t shutdown after two, Ju St quit.
      This.readCheckTimer.Dispose (shutdownevent);
      Shutdownevent.waitone (timespan.frommilliseconds);
      This.writeCheckTimer.Dispose (shutdownevent);
      Shutdownevent.waitone (timespan.frommilliseconds);
      Definition of WaitOne: public virtual bool WaitOne (TimeSpan timeout,bool exitcontext)
      this.asyncTasks.Shutdown ();
      This.asynctasks = null;
      This.asyncwritetask = null;
      This.asyncerrortask = null;}}}


3, run ACTIVEMQ, find activemq after the unpacked Bin folder: ... \apache-activemq-5.3.1\bin, Execute the Activemq.bat batch file to start the ACTIVEMQ server with the default port of 61616, which can be modified in the configuration file.

4, write C # program to achieve ACTIVEMQ simple application. Create a new C # project (a Producter project and a consumer project), WinForm, or the console program, where the console project is built, Add a reference to Apache.NMS.dll and Apache.NMS.ActiveMQ.dll, and then you can write the implementation code, and the simple producer and consumer implementation code is as follows:

Producer

Using System;
Using System.Collections.Generic;
Using System.Text;
Using Apache.nms;
Using Apache.NMS.ActiveMQ;
Using System.IO;
Using System.Xml.Serialization;
Using System.Runtime.Serialization.Formatters.Binary; Namespace Publish {class Program {static void Main (string[] args) {try {//create the C
        Onnection Factory iconnectionfactory Factory = new ConnectionFactory ("tcp://localhost:61616/"); using (iconnection connection = factory. CreateConnection ()) {//create the session using (ISession session = connection. CreateSession ()) {//create The Producer for the topic/queue imessageproducer prod = ses Sion.
            Createproducer (New Apache.NMS.ActiveMQ.Commands.ActiveMQTopic ("testing"));
            Send Messages int i = 0; while (! console.keyavailable) {itextmessage msg = prod.
              Createtextmessage (); Msg. Text = i.tostring ();
              Console.WriteLine ("Sending:" + i.tostring ()); Prod.
              Send (msg, Apache.NMS.MsgDeliveryMode.NonPersistent, Apache.NMS.MsgPriority.Normal, Timespan.minvalue);
              System.Threading.Thread.Sleep (5000);
            i++;
      }} console.readline ();
        catch (System.Exception e) {Console.WriteLine ("{0}", e.message);
      Console.ReadLine ();

 }
    }
  }
}

Consumer:

Using System;
Using System.Collections.Generic;
Using System.Text;
Using Apache.nms;
Using Apache.NMS.ActiveMQ;
Using System.IO;
Using System.Xml.Serialization;
Using System.Runtime.Serialization.Formatters.Binary;  Namespace Subscribe {class Program {static void Main (string[] args) {try {//create the
        Connection Factory Iconnectionfactory factory = new ConnectionFactory ("tcp://localhost:61616/"); Create the connection using (iconnection connection = factory. CreateConnection ()) {connection.
          ClientId = "Testing listener"; Connection.
          Start (); Create the session using (ISession session = connection. CreateSession ()) {//create the Consumer imessageconsumer Consumer = session.
            Createdurableconsumer (New Apache.NMS.ActiveMQ.Commands.ActiveMQTopic ("testing"), "testing listener", NULL, FALSE); Consumer. Listener + = new MessageListener (consumeR_listener);
          Console.ReadLine (); } connection.
          Stop (); Connection.
        Close ();
      The catch (System.Exception e) {Console.WriteLine (e.message); }} static void Consumer_listener (IMessage message) {try {itextmessage msg = (Itextmessa
        GE) message; Console.WriteLine ("Receive:" + MSG.)
      Text);
      catch (System.Exception e) {Console.WriteLine (e.message);

 }
    }
  }
}

Program Implementation function: Producer producer Create a theme named testing, and send a message to the subject every 5 seconds, consumers consumer subscribe to the testing theme so long as the producer sends the testing message to the ACTIVEMQ server, The server sends the message to consumers who subscribe to the testing theme.

The compiler generates Producer.exe and Consumer.exe, and executes two EXE to see the message sent and received.

This example is built on the theme (Topic), ACTIVEMQ also support another way: Queue, that is peer-to-peer, what is the difference between the two? The difference is that topic is broadcast, that is, if a topic is subscribed to by multiple consumers, the server sends the message to all consumers as soon as a message arrives at the server, and the queue is point-to-point, that is, a message can only be sent to a consumer, if a queue is subscribed to by multiple consumers, If there is no special situation, the message will be sent to different consumers one by one, for example:

Msg1-->consumer A

Msg2-->consumer B

Msg3-->consumer C

Msg4-->consumer A

Msg5-->consumer B

Msg6-->consumer C

Special cases refer to: ACTIVEMQ support filtering mechanism, that is, the producer can set the properties of the message (properties), which corresponds to the selector of the consumer side, only the selector of the consumer settings match the properties of the message, The message will be sent to the consumer. Both topic and queue support Selector.

How should properties and selector be set? Please see the following code:

Producer

Itextmessage msg = prod. Createtextmessage ();
Msg. Text = i.ToString ();
Msg. Properties.setstring ("Myfilter", "test1");
Console.WriteLine ("Sending:" + i.tostring ());
Prod. Send (msg, Apache.NMS.MsgDeliveryMode.NonPersistent, Apache.NMS.MsgPriority.Normal, Timespan.minvalue);

Consumer

Selector Imessageconsumer consumer = Session is set by parameter when generating consumer
. Createconsumer (New Apache.NMS.ActiveMQ.Commands.ActiveMQQueue ("testing"), "myfilter= ' test1 '");

Read more about C # Interested readers can view the site topics: "C # form Operation Tips Summary", "C # Common control usage Tutorial", "WinForm Control Usage Summary", "C # Programming Thread Usage Skills summary", "C # Operation Excel Skills Summary", "C # Summary of operational skills in XML files, C # tutorial on data structure and algorithms, C # array operation techniques Summary, and C # Introduction to object-oriented Programming

I hope this article will help you with C # programming.

Related Article

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.