Apache ActiveMQ 5 with .Net Core 3.1 and C#

Hi All..
 
In this post I'm going to explain how to use Apache ActiveMQ 5 (which is a popular Java based messaging server) for .Net Core 3.0+ with C#. 
Let's get started.

Prerequisites
1. Visual Studio (I'll be using 2019 Community) 
2. .Net Core framework (I'll be using 3.1)
3. Java JDK or JRE Installed and Java Environment variable has been set (Since I'm doing in a Windows 10 computer) 

Ok.. If you have the above requirements then let's get start the actual work.

1. Download and install ActiveMQ 5 
  • Go to http://activemq.apache.org/components/classic/download/ and download according to your operating system. 
  • I'll download .zip package for Windows
2. Copy the .zip file and put it inside a folder as you like or install with the installers if you download the installer. 
  • If you got the .zip file like me; then extract it inside the folder that you paste the .zip file
  • Then you will get a folder with the ActiveMQ package 
3. Start the Active MQ Server 
  • Open the command prompt and go to the bin folder inside the ActiveMQ package. In my case it is D:\Development\Tools\apache-activemq-5.16.0\bin
  • Then type command activemq start
  • Then your command prompt will print many information regarding the ActiveMQ starting and running with the default ports to access.
4. Access the Admin portal of ActiveMQ Server 
  • Go to your browser and type http://localhost:8161/admin/
  • Then a dialog box will popup to sign in to the ActiveMQ admin portal. 
  • Use the default username - "admin" and password - "admin"
  • Click Sign In
  • Then you will get the following screen. 
5. Check if the ActiveMQ is listening to the default port; which is 61616.
  • Open another command prompt.
  • Type netstat -an|find "61616"
  • Then you have to get results as listening as bellow.


Ok.. Now our ActiveMQ server is up and running and it is listing to the 61616 port. 
All good.

Now let's start the coding which is my favorite part.
We are not going to create a complex system to test this. The focus is to how to create message producer and consumer using .Net Core and C#.

So, I'm going to create a simple console application. 

5. Create a Console App (.Net Core)
  • Open Visual Studio and click on Create a New Project. 
  • Type "console" in the search section.
  • Then Select "Console App (.Net Core)
  • Give it a name as you like and select a location to save your project. 
6. Install the Apache ActiveMQ libraries for .Net Core

NOTE: There is a .Net 4.0+ version of this library. Since we are using this in a .Net Core project we have to use the .Net Core libraries. 
  • Right click on the project and select "Manage NuGet packages..."
  • Type "Apache.NMS.NetCore" in the search section of NuGet packages. 
  • Select the package "Apache.NMS.ActiveMQ.NetCore" and click on install. 
  • This will install the Apache.NMS.NetCore dependency as well. 
7. Create a Message Producer
  • Create a new class file in the project and give it a name. 
  • I'm naming as "Producer"
  • Then copy this content to your file.
using System;
using System.Threading;
using Apache.NMS;
using Apache.NMS.ActiveMQ;
using Apache.NMS.Util;

namespace ActiveMqConsole
{
    public class Producer
    {
        protected static AutoResetEvent semaphore = new AutoResetEvent(false);
        protected static ITextMessage message = null;
        protected static TimeSpan receiveTimeout = TimeSpan.FromSeconds(10);
        Uri connecturi = new Uri("tcp://localhost:61616");

        public void ProduceMessage()
        {
            try
            {
                IConnectionFactory factory = new ConnectionFactory(connecturi);
                IConnection connection = factory.CreateConnection();
                ISession session = connection.CreateSession();
                IDestination destination = SessionUtil.GetDestination(session, "queue://mycorequeue");
                IMessageProducer producer = session.CreateProducer(destination);
                connection.Start();
                producer.DeliveryMode = MsgDeliveryMode.Persistent;
                producer.RequestTimeout = receiveTimeout;

                // Send a message
                ITextMessage request = session.CreateTextMessage("Hello World!");
                request.NMSCorrelationID = "abc";

                producer.Send(request);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }
}

8. Create a Message Consumer
  • Create a new class file in the project and give it a name. 
  • I'm naming as "Consumer"
  • Then copy this content to your file.
using System;
using System.Threading;
using Apache.NMS;
using Apache.NMS.ActiveMQ;
using Apache.NMS.Util;

namespace ActiveMqConsole
{
    public class Consumer
    {
        protected static AutoResetEvent semaphore = new AutoResetEvent(false);
        protected static ITextMessage message = null;
        protected static TimeSpan receiveTimeout = TimeSpan.FromSeconds(10);
        Uri connecturi = new Uri("tcp://localhost:61616");

        public void ConsumeMessage()
        {
            try
            {
                IConnectionFactory factory = new ConnectionFactory(connecturi);
                IConnection connection = factory.CreateConnection();
                ISession session = connection.CreateSession();
                IDestination destination = SessionUtil.GetDestination(session, "queue://mycorequeue");
                IMessageConsumer consumer = session.CreateConsumer(destination);
                connection.Start();
                consumer.Listener += new MessageListener(OnMessage);
                semaphore.WaitOne((int)receiveTimeout.TotalMilliseconds, true);
                if (message == null)
                {
                    Console.WriteLine("No message received!");
                }
                else
                {
                    Console.WriteLine("Received message with ID:   " + message.NMSMessageId);
                    Console.WriteLine("Received message with text: " + message.Text);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        protected static void OnMessage(IMessage receivedMsg)
        {
            message = receivedMsg as ITextMessage;
            semaphore.Set();
        }
    }
}

Ok..
Now our message producer and consumer are ready. 
Let's give it a try..

To do this I'm going to change the program.cs

9. Test the Message Producer
  • Open Program.cs 
  • Create a new instance of Producer and call ProduceMessage method.
namespace ActiveMqConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            var producer = new Producer();
            producer.ProduceMessage();
        }
    }
}
  • Save and Run the project. 
10. Check the ActiveMQ admin portal
  • Go to http://localhost:8161/admin/queues.jsp
  • Then you will see there is a new Queue named "mycorequeue"; which we gave.
  • Notice that under Number Of Pending Messages shows as 1 and under Messages Dequeued column it shows as 0.
  • Then you will see there is a new message. 


  • Click on that message. 
  • And there you see our message text. 




11. Test the Message Consumer
  • Open Program.cs 
  • Comment out the producer code for now. 
  • Create a new instance of Consumer and call ConsumeMessage method.
namespace ActiveMqConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            //var producer = new Producer();
            //producer.ProduceMessage();

            var consumer = new Consumer();
            consumer.ConsumeMessage();
        }
    }
}
  • Save and Run the project. 
  • In the Console you'll see it read the message. 


12. Check the ActiveMQ admin portal
  • Go to http://localhost:8161/admin/queues.jsp
  • Refresh the page. 
  • Notice that now under Number Of Pending Messages it shows as 0 and under Messages Dequeued column it shows as 1.
  • And if you click on the queue it is now empty. 

There you go..
We just created a simple queue in ActiveMQ, send a message to it and read the message with .Net Core and C#. 







Comments

Popular posts from this blog

Deploy Angular 8 app to Azure with Azure DevOps

Firebase with.Net Core and C#