In this blog post, we will create a simple REST API in C# using the Apache ActiveMQ messaging service to demonstrate a request/response pattern. The API will send a message with the text “Hello” to an ActiveMQ queue, and the response will return a greeting based on the day of the week.
This tutorial is beginner-friendly and will walk you through the steps to set up ActiveMQ, send a message, and process a response in C#. Let’s get started!
What You’ll Need
- Apache ActiveMQ: A powerful open-source messaging server.
- .NET 6/7/8 SDK: For building the C# application.
- NuGet Packages:
Apache.NMS.ActiveMQ
: For connecting to ActiveMQ.Apache.NMS
: Messaging API for ActiveMQ.
Step 1: Install Apache ActiveMQ
- Download ActiveMQ:
Visit Apache ActiveMQ’s website and download the latest version. - Start ActiveMQ:
Extract the downloaded archive, navigate to thebin
directory, and start the server:- On Windows:
activemq.bat start
- On Linux/Mac:
./activemq start
- On Windows:
- Access Admin Console:
Once started, you can access the ActiveMQ admin console at http://localhost:8161.
Step 2: Set Up a New C# Project
- Create a new ASP.NET Core Web API project:
dotnet new webapi -n ActiveMQExample cd ActiveMQExample
- Add the required NuGet packages:
dotnet add package Apache.NMS.ActiveMQ dotnet add package Apache.NMS
Step 3: Configure ActiveMQ in Your Application
Add a Configuration Class
Create a MessageBrokerConfig.cs
file to configure the connection to ActiveMQ:
using Apache.NMS;
using Apache.NMS.ActiveMQ;
namespace ActiveMQExample.Config;
public class MessageBrokerConfig
{
private readonly string _brokerUri = "tcp://localhost:61616"; // Default ActiveMQ URI
private readonly string _queueName = "GreetingQueue";
private IConnectionFactory? _factory;
public ISession CreateSession()
{
_factory ??= new ConnectionFactory(_brokerUri);
var connection = _factory.CreateConnection();
connection.Start();
return connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
}
public string QueueName => _queueName;
}
Step 4: Implement the API Logic
Create a Controller
In the Controllers
folder, create a file named GreetingController.cs
:
using Apache.NMS;
using ActiveMQExample.Config;
using Microsoft.AspNetCore.Mvc;
namespace ActiveMQExample.Controllers;
[ApiController]
[Route("api/[controller]")]
public class GreetingController : ControllerBase
{
private readonly MessageBrokerConfig _brokerConfig;
public GreetingController()
{
_brokerConfig = new MessageBrokerConfig();
}
[HttpPost("send")]
public IActionResult SendMessage([FromBody] string message)
{
try
{
using var session = _brokerConfig.CreateSession();
var destination = session.GetQueue(_brokerConfig.QueueName);
// Producer sends the message
using var producer = session.CreateProducer(destination);
var textMessage = session.CreateTextMessage(message);
producer.Send(textMessage);
return Ok("Message sent successfully!");
}
catch (Exception ex)
{
return StatusCode(500, $"Error: {ex.Message}");
}
}
[HttpGet("receive")]
public IActionResult ReceiveMessage()
{
try
{
using var session = _brokerConfig.CreateSession();
var destination = session.GetQueue(_brokerConfig.QueueName);
// Consumer receives the message
using var consumer = session.CreateConsumer(destination);
var message = consumer.Receive(TimeSpan.FromSeconds(10)) as ITextMessage;
if (message == null)
return NotFound("No messages in the queue.");
// Generate greeting based on the day of the week
var dayOfWeek = DateTime.Now.DayOfWeek.ToString();
var response = $"Hello! Today is {dayOfWeek}. Have a great day!";
return Ok(response);
}
catch (Exception ex)
{
return StatusCode(500, $"Error: {ex.Message}");
}
}
}
Step 5: Test the API
Sending a Message
- Start your application:
dotnet run
- Use Postman, curl, or a browser to send a message:
curl -X POST http://localhost:5000/api/greeting/send -H "Content-Type: application/json" -d "\"Hello Ravi\""
- You should see a response:
"Message sent successfully!"
Receiving the Response
- Call the receive endpoint:
curl http://localhost:5000/api/greeting/receive
- You’ll get a response like:
"Hello! Today is Monday. Have a great day!"
Wrapping Up
Congratulations! 🎉 You’ve built a simple REST API that uses the Apache ActiveMQ request/response pattern in C#.
Here’s a quick summary of what we did:
- Set up Apache ActiveMQ as the message broker.
- Created a C# application to send and receive messages.
- Used the request/response pattern to generate greetings based on the day of the week.
This is just the beginning—you can use this pattern to build more advanced messaging systems, such as for order processing, real-time notifications, or IoT communication.
Happy coding! 🚀