Integration of ActiveMQ with .NET Core Console Application

In this article, we delve into the seamless integration of Apache ActiveMQ, a powerful open-source message broker, with a .NET Core console application. Let’s explore the setup, implementation, and benefits of this integration for modern application development.

Introduction to ActiveMQ and .NET Core Console App Integration


Apache ActiveMQ and its Messaging Capabilities

Apache ActiveMQ is a robust, open-source message broker that facilitates asynchronous communication between distributed applications. It implements the Java Message Service (JMS) API and provides support for various messaging patterns, including publish-subscribe and point-to-point communication. ActiveMQ is known for its reliability, scalability, and extensive features, making it a popular choice for building messaging solutions in various industries.

ActiveMQ serves as a message-oriented middleware (MOM) that enables the decoupling of components in a distributed system by allowing them to communicate asynchronously through messages. Some key features and capabilities of Apache ActiveMQ include

  1. Messaging Protocols: ActiveMQ supports multiple messaging protocols, including OpenWire, MQTT, and STOMP, allowing clients to connect using various technologies and programming languages.
  2. Persistence: Messages can be persisted in different storage options like JDBC, file system, or relational databases, ensuring data durability.
  3. Clustering: ActiveMQ can be configured in a cluster to enhance scalability and fault tolerance.
  4. Message Groups: It supports the concept of message groups for ordered message processing within a consumer group.
  5. Message Filtering: ActiveMQ enables message filtering based on header properties, making it efficient for routing and selecting specific messages.
  6. Security: It provides security features such as authentication and authorization, ensuring message confidentiality and integrity.

ActiveMQ

Introduction to .NET Core and Its Relevance for Messaging Applications

.NET Core is a cross-platform, open-source framework developed by Microsoft for building modern, high-performance applications. .NET Core’s versatility extends to messaging applications, making it a suitable platform for integrating with ActiveMQ. Its relevance for messaging applications lies in its ability to.

  1. Cross-Platform Compatibility: .NET Core allows you to develop messaging applications that can run on different operating systems, making it versatile for building cross-platform solutions.
  2. High Performance: .NET Core is known for its speed and efficiency, making it suitable for building high-throughput messaging systems.
  3. Microservices Architecture: .NET Core is often used in microservices-based architectures, where messaging plays a crucial role in inter-service communication.
  4. Containerization: .NET Core applications can be containerized using technologies like Docker, simplifying deployment and scaling in container orchestration platforms like Kubernetes.
  5. Integration Libraries: .NET Core provides libraries and tools for integrating with various messaging systems, including ActiveMQ, through libraries like Apache.NMS and Apache.NMS.ActiveMQ.

In the subsequent sections of this article, we will delve deeper into the process of integrating ActiveMQ with .NET Core, exploring the setup and implementation for building efficient messaging solutions.

Setting Up ActiveMQ with .NET Core Console App

To begin integrating Apache ActiveMQ with .NET Core, you’ll need to set up your development environment and configure ActiveMQ. This section will guide you through the process.

Installing and Configuring Apache ActiveMQ

Download ActiveMQ: Visit the official Apache ActiveMQ website (https://activemq.apache.org/) and download the latest version of ActiveMQ. Choose the distribution package that suits your operating system. For this guide, I have downloaded the ActiveMQ (apache.org) Version 5.16.4 zip folder in my local system.

ActiveMQ 5.16.4 Realse

Installation: Install ActiveMQ by following the installation instructions provided for your specific platform. Typically, this involves unzipping or extracting the downloaded package to a directory of your choice.

Start ActiveMQ: Navigate to the ActiveMQ installation directory and run the appropriate script or executable to start the ActiveMQ broker. On many systems, this can be done by executing the “activemq start” from bin folder.

Access the Admin Console: ActiveMQ provides a web-based admin console that you can access via a web browser. By default, it’s available at http://localhost:8161/admin/. Use this console to monitor and manage your ActiveMQ instance. First, it will ask for a username and password, so enter.

  • Username: admin
  • Password: admin

Sign in

After this, your Apache ActiveMQ Console of localhost will be open.

 Apache ActiveMQ

Setting Up the Development Environment

Create a .NET Core Console App Project: Create a new .NET Core Console App project or navigate to an existing project.

Add Dependencies: In your project, you’ll need to add the necessary dependencies for working with ActiveMQ. You can use the Apache.NMS and Apache.NMS.ActiveMQ libraries, which provide .NET Core bindings for ActiveMQ. Add these packages to your project using a package manager like NuGet:

  • dotnet add package Apache.NMS
  • dotnet add package Apache.NMS.ActiveMQ

Console App Project Code

Code representation

Code representation

appsettings.json

This file contains the queue name and file paths.

appsettings.json Code

Program.cs

In the Program file, first, I have added appsettings.json to get the name of the request queue and file path where data resides, then read all the data from xml request data file and sent to Request Queue (SendMessage) and Receive that message (ReceiveMessages).

using Apache.NMS;
using Microsoft.Extensions.Configuration;
using IConnectionFactory = Apache.NMS.IConnectionFactory;

class Program
{
    static void Main(string[] args)
    {
        var builder = new ConfigurationBuilder();
        builder.SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
        IConfiguration config = builder.Build();
        string? brokerUri = config.GetSection("ActiveMQ").GetSection("BrokerUri").Value;
        string? requestQueueName = config.GetSection("ActiveMQ").GetSection("RequestQueueName").Value;
        Dictionary<string, string>? requestFilePath = config.GetSection("Path:RequestFilePath").Get<Dictionary<string, string>>();
        string xmlResponseContent = string.Empty;
        // Loop through the RequestFilePaths  if there are more than one
        foreach (var keyValuePair in requestFilePath)
        {
            string fileType = keyValuePair.Key;
            string filePath = keyValuePair.Value.ToString();
            xmlResponseContent = System.IO.File.ReadAllText(filePath);
            // Send messages to the queue
            SendMessage(brokerUri, requestQueueName, xmlResponseContent);
        }
        Thread.Sleep(120);
        // Receive messages from the queue
        ReceiveMessages(brokerUri, "RequestQueue");
        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
    static void SendMessage(string brokerUri, string queueName, string message)
    {
        Apache.NMS.IConnectionFactory factory = new NMSConnectionFactory(brokerUri);
        using (IConnection connection = factory.CreateConnection())
        {
            try {
            connection.Start();
            using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
            {
                IDestination destination = session.GetQueue(queueName);
                using (IMessageProducer producer = session.CreateProducer(destination))
                {
                    ITextMessage textMessage = producer.CreateTextMessage(message);
                    producer.Send(textMessage);
                    //Console.WriteLine("Message sent: " + textMessage.Text);
                }
            }
        }
            catch (Exception ex)
            {
                Console.WriteLine("Error occurred: " + ex.Message);
            }
            finally
            {
                if (connection != null && connection.IsStarted)
                {
                    connection.Stop();
                    connection.Close();
                }
            }
        }
    }
    static void ReceiveMessages(string brokerUri, string queueName)
    {
        IConnectionFactory factory = new NMSConnectionFactory(brokerUri);
        using (IConnection connection = factory.CreateConnection())
        {
            try
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                {
                    IDestination destination = session.GetQueue(queueName);
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                    {
                        while (true)
                        {
                            IMessage message = consumer.Receive();
                            if (message is ITextMessage textMessage)
                            {
                                Console.WriteLine("Received message: " + textMessage.Text);
                            }
                            else if (message == null)
                            {
                                // No more messages in the queue
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occurred: " + ex.Message);
            }
            finally
            {
                if (connection != null && connection.IsStarted)
                {
                    connection.Stop();
                    connection.Close();
                }
            }
        }
    }
}

Now, run the app and navigate to your active MQ URL on the browser. Go to the Queues Tab and find your request queue.

Request Queue

Click on your Queue, and you will find your data there.

Browse request data

Now select the Message ID and check your data.

Check data

Data is stored in the request queue.

Now, it’s time to pick the data and print it on the console.

As I put thread.sleep between send and receive, so after some time, it will receive data and print to my console.

Console Output

Console output

Summary

In this blog, we explored the integration of Apache ActiveMQ with a .NET Core console application, highlighting the essential steps to set up both the messaging broker and the development environment. We discussed the significance of ActiveMQ in enabling asynchronous communication and the versatility of .NET Core for building cross-platform, high-performance messaging solutions.

With ActiveMQ configured and the .NET Core application in place, we demonstrated how to send messages to a queue and subsequently receive those messages. This integration allows for efficient communication between components in distributed systems, making it a valuable addition to modern application architectures.

By combining the robust capabilities of ActiveMQ with the agility of .NET Core, developers can harness the power of asynchronous messaging for building scalable and resilient applications across diverse platforms and use cases.


Similar Articles