SoFunction
Updated on 2025-03-08

Methods for C# to realize communication with Active MQ

This article describes the method of C# to realize communication with Active MQ. Share it for your reference, as follows:

Content summary:

It mainly introduces how to use C# to achieve communication with Active MQ in the form of source code. This article assumes that you have installed JDK1 correctly, understand Active MQ and have a certain programming foundation.

text:

The ultimate goal of JMS programs is to produce and consume messages that can be used by other programs. JMS Message is a basic format that is both simple and flexible, allowing the creation of messages that conform to non-JMS program formats on different platforms.
Message consists of three parts: message header, attribute and message body.
Active MQ supports filtering mechanism, that is, producers can set the Properties of the message, which corresponds to the Selector on the consumer side. Only when the selector set by the consumer matches the Properties of the message, the message will be sent to the consumer. Both Topic and Queue support Selector.

Sample code:

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
/*
  * Function description: C# using ActiveMQ example
  * Number of modifications: 2
  * Last updated: by Kagula, 2012-07-31
  *
  * Prerequisites:
  * [1]apache-activemq-5.4.2
  * [2]-1.5.6-bin
  * [3] WinXP SP3
  * [4]VS2008 SP1
  * [5]WPF Project With .NET Framework 3.5
  *
  * start up
  *
  * Start without safety control
  * [Your decompression path]\apache-activemq-5.4.2\bin\
  *
  * Safe mode startup
  * Add environment variable: ACTIVEMQ_ENCRYPTION_PASSWORD=activemq
  * [Your decompression path]\apache-activemq-5.4.2\bin>activemq xbean:file:../conf/
  *
  * Active MQ Management Address
  * http://127.0.0.1:8161/admin/
  * Added access to "http://127.0.0.1:8161/admin/"
  *
  * Step 1: Add access restrictions
  * Modify D:\apache\apache-activemq-5.4.2\conf\file
  * The following line code, original
  * <property name="authenticate" value="true" />
  * Modified to
  * <property name="authenticate" value="false" />
  *
  * Step 2: Change the login username and password, the default is admin and admin
  * D:\apache\apache-activemq-5.4.2\conf\
  *
  * User Management (Preparation: Start ActiveMQ in a secure manner)
  *
  * Modify the default username and password in the [your decompression path]\apache-activemq-5.4.2\conf\ file
  * You can add a new username in the [your decompression path]\apache-activemq-5.4.2\conf\ file
  *. Add OA user with password and username.
  * <authenticationUser username="oa" password="oa" groups="users,admins"/>
  *
  * In the [your decompression path]\apache-activemq-5.4.2\conf\ file, you can also set the specified Topic or Queue
  * Can only be read or write by which user groups.
  *
  *
  * Configure C# with WPF project
  * The [Application]->[TargetFramework] property of the project is set to [.NETFramework 3.5] (this is the default setting for the VS2008WPF project)
  * Add a reference to [your decompression path]\-1.5.6-bin\lib\net-3.5\
  * Equivalent to interface
  *
  * If debugging
  * Put the [your decompression path]\-1.5.6-bin\build\net-3.5\debug\ directory
  * Copy the file to the Debug directory of your project
  * Equivalent to implementation
  *
  * If debugging in Release
  * Refer to the above article, go to the corresponding DLL file in the Release directory and copy it to the Release directory of your project.
  *
  *
  * References
  * [1] "C# call ActiveMQ official example" /nms/
  * [2]《ActiveMQ NMS Download Address》/nms/
  * [3] "Example of Application of Active MQ in C#" https:///article/
  * [4] "NMS API Reference"/nms/
  */
namespace testActiveMQSubscriber
{
  /// &lt;summary&gt;
  /// Interaction logic for 
  /// &lt;/summary&gt;
  public partial class Window1 : Window
  {
    private static IConnectionFactory connFac;
    private static IConnection connection;
    private static ISession session;
    private static IDestination destination;
    private static IMessageProducer producer;
    private static IMessageConsumer consumer;
    protected static ITextMessage message = null;
    public Window1()
    {
      InitializeComponent();
      initAMQ("MyFirstTopic");
    }
    private void initAMQ(String strTopicName)
    {
      try
      {
        connFac = new NMSConnectionFactory(new Uri("activemq:failover:(tcp://localhost:61616)"));
        // Create a new connection        //connection = ("oa","oa");//Set the username and password to use to connect        //If you want to "subscribe" for a long time, you need to set the ClientId so that the program will be stopped during operation and will be able to get the messages you have not received when it is resumed!         = "testing listener";
        connection = ();//If you start Active MQ service by default, you do not need to fill in your username or password        //Create Session        session = ();
        //Publish/Subscribe mode, suitable for one-to-many situations        destination = (session, "topic://" + strTopicName);
        // Create a new producer object        producer = (destination);
         = ;// After the ActiveMQ server stops working, the message is no longer retained        //New consumer object: Normal "subscribe" mode        //consumer = (destination);//Does not require a persistent "subscription"        // Create a new consumer object: persistent "subscribe" mode:        // After persisting "subscribe", if your program is stopped and resumes running.        // Starting from the first persistent subscription, you can continue to receive messages that have not been received        consumer = (
          (strTopicName)
          , , null, false);
        //Set message reception event         += new MessageListener(OnMessage);
        //Start message listening from Active MQ        ();
      }
      catch (Exception e)
      {
        //Initializing ActiveMQ connection failed, write error information to the Output window of VS2008!        ();
      }
    }
    private void SendMsg2Topic_Click(object sender, RoutedEventArgs e)
    {
      //Send a message      ITextMessage request = (()+" "+);
      (request);
    }
    protected void OnMessage(IMessage receivedMsg)
    {
      //Receive message      message = receivedMsg as ITextMessage;
      //UI thread, display the received message      (, new Action(() =&gt;
      {
        DateTime dt = new DateTime();
        ListBoxItem lbi = new ListBoxItem();
         = () + " " + ;
        (lbi);
      }));
    }
  }
}

Queue communication method, consumer example

using System;
using ;
using ;
using ;
using ;
using ;
using log4net;
using ;
using ;
namespace Cat8637AutoCallServer
{
  public class SMTask
  {
    public String Callee { get; set; }
    public String CheckNumber { get; set; }
    public int Deadline { get; set; }
    public override String ToString()
    {
      return ("Callee={0},CheckNumber={1},Deadline={2}",
        Callee,CheckNumber,Deadline);
    }
  }
  /*
    * Responsible for receiving tasks and putting tasks in the task waiting queue.
    */
  public class MQClient
  {
    private static readonly ILog logger = (typeof(MQClient));
    private static IConnection connection = null;
    private static ISession session = null;
    Queue _voiceSMTasks = new Queue();
    public MQClient()
    {
      try
      {
        IConnectionFactory factory = new NMSConnectionFactory(new Uri("activemq:failover:(tcp://localhost:61616)"));
        // Create a new connection        //connection = ("oa","oa");//Set the username and password to use to connect        connection = ();
        session = ();
        IMessageConsumer consumer = (("TaskIssue_VoiceSM"));
         += new MessageListener(OnMessage);
        ();
      }
      catch (Exception ex)
      {
        ();
      }
    }
    protected void OnMessage(IMessage receivedMsg)
    {
      IMessage message = receivedMsg as ITextMessage;
      SMTask smTask = new SMTask();
       = ["Callee"] as String;
       = ["Message"] as String;
       = Convert.ToInt32(["deadline"] as String);
      ("Received: "+());
      lock (_voiceSMTasks)
      {
        _voiceSMTasks.Enqueue(smTask);
      }
    }
    public SMTask GetVoiceSMTask()
    {
      SMTask result = null;
      lock (_voiceSMTasks)
      {
        if (_voiceSMTasks.Count &gt; 0)
        {
          result = _voiceSMTasks.Dequeue() as SMTask;
        }
      }
      return result;
    }
  }
}

Queue communication method, producer example

private void Send_Click(object sender, RoutedEventArgs e)
{
  try
  {
    IDestination destination = (session, "queue://TaskIssue_VoiceSM");
    // Create a new producer object    IMessageProducer producer = (destination);
     = ;// After the ActiveMQ server stops working, the message is no longer retained    ITextMessage request = ();
     = "TestVoiceSM";//Here I filled in the name of the application.    ["Callee"] = ;
    ["Message"] = ;
    ["deadline"] = ;
    (request);
  }
  catch (Exception ex)
  {
    //Initializing ActiveMQ connection failed, write error information to the Output window of VS2008!    ();
  }
}
private void Window_Closed(object sender, EventArgs e)
{
  try
  {
    if (session == null)
      return;
    //if (connection == null)
    //  return;
    ();
    //();
  }
  catch (Exception ex)
  {
    ();
  }
}

For more information about C# related content, please check out the topic of this site:Summary of C# form operation skills》、《Tutorial on the usage of common C# controls》、《Summary of WinForm control usage》、《Summary of thread usage techniques for C# programming》、《Summary of C# operation skills》、《Summary of XML file operation skills in C#》、《C# data structure and algorithm tutorial》、《Summary of C# array operation skills"and"Introduction to C# object-oriented programming tutorial

I hope this article will be helpful to everyone's C# programming.