Thursday, January 05, 2023

Azure Series : RabbitMQ - Setup and Use - Building a Message Queue in RabbitMQ and Publish Message

Introduction

In today's interconnected and distributed systems, message queues play a crucial role in ensuring reliable communication between various components. RabbitMQ, a popular open-source message broker, provides a robust and scalable solution for implementing message queues. In this article, we will explore how to create a message queue in RabbitMQ using ASP.NET  Core and C#.

Prerequisites

Before we dive into the implementation, make sure you have the following tools installed:

  1. .NET Core SDK (version compatible with ASP.NET  Core)
  2. RabbitMQ server (either locally or on a cloud-based service)

Step 1: Set up the RabbitMQ Server

First, ensure you have RabbitMQ installed and running. You can download and install it from the official website or use a cloud-based service like RabbitMQ Cloud or CloudAMQP. You can also install it locally on your machine or use Docker to run RabbitMQ

Step 2: Create an ASP.NET  Core Project

Open your terminal or command prompt and create a new ASP.NET  Core project using the following command:

bash
dotnet new webapi -n MessageQueueExample
cd MessageQueueExample

Step 3: Install RabbitMQ Client Library

Next, install the RabbitMQ.Client NuGet package, which allows our ASP.NET  Core application to communicate with the RabbitMQ server:

dotnet add package RabbitMQ.Client

Step 4: Implement the Message Queue

Now, let's create a MessageQueueService class to handle interactions with the RabbitMQ server. Inside the Services folder, create a new file named MessageQueueService.cs.

using RabbitMQ.Client;
using System;
using System.Text;

namespace MessageQueueExample.Services
{
    public class MessageQueueService : IDisposable
    {
        private readonly IConnection _connection;
        private readonly IModel _channel;
        private const string QueueName = "my_queue";

        public MessageQueueService()
        {
            var factory = new ConnectionFactory() { HostName = "localhost" }; // Replace "localhost" with your RabbitMQ server address if needed
            _connection = factory.CreateConnection();
            _channel = _connection.CreateModel();
            _channel.QueueDeclare(queue: QueueName, durable: false, exclusive: false, autoDelete: false, arguments: null);
        }

        public void SendMessage(string message)
        {
            var body = Encoding.UTF8.GetBytes(message);
            _channel.BasicPublish(exchange: "", routingKey: QueueName, basicProperties: null, body: body);
        }

        public void Dispose()
        {
            _channel.Close();
            _connection.Close();
        }
    }
}

Step 5: Configure Dependency Injection

In the Startup.cs file, configure the MessageQueueService to be injected into the application:

using MessageQueueExample.Services;
// ...

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddSingleton<MessageQueueService>();
    // ...
}

Step 6: Sending Messages

Now that our message queue service is ready, let's use it to send messages. In your desired controller, inject the MessageQueueService, and use it to send a message:

using Microsoft.AspNetCore.Mvc;
using MessageQueueExample.Services;
// ...

[ApiController]
[Route("api/[controller]")]
public class MessageController : ControllerBase
{
    private readonly MessageQueueService _messageQueueService;

    public MessageController(MessageQueueService messageQueueService)
    {
        _messageQueueService = messageQueueService;
    }

    [HttpPost]
    public IActionResult SendMessage([FromBody] string message)
    {
        _messageQueueService.SendMessage(message);
        return Ok("Message sent successfully!");
    }
}

Conclusion

Congratulations! You have successfully implemented a message queue in RabbitMQ using ASP.NET  Core and C#. This setup will allow your applications to communicate efficiently and reliably, enabling a more scalable and resilient architecture.

Remember to handle error scenarios and add appropriate exception handling in a real-world scenario. Additionally, consider implementing message processing on the consumer side for a complete message queue system. Happy coding!

Wednesday, January 04, 2023

Azure Series : RabbitMQ - Setup and Use - Install RabbitMQ

Install RabbitMQ

If you plan on to host RabbitMQ locally, you can either install RabbitMQ in your local workspace or run a RabbitMQ Docker container in your local workspace.

To install RabbitMQ in your local workspace:

  1. Make sure you have already installed Chocolatey Package Manager
  2. RunAsAdministrator - Windows Powershell
  3. From the powershell prompt run the following command to install RabbitMQ:
    choco install rabbitmq
  4. Follow the installation prompts
  5. After the installation completes if you have no critical errors, RabbitMQ should now be installed in your local workspace.
  6. To verify RabbitMQ is now running in your local workspace, open a browser window and go to the following URL:
    http://localhost:15672/ 
  7. You should see a login screen for the RabbitMQ web interface. The default RabbitMQ username and password is as follows:


To install RabbitMQ in your docker:

  1. Make sure you have installed Docker. 
  2. RunAsAdministrator - Windows Powershell
  3. First, let’s pull the RabbitMQ docker image. We’ll use the 3-management version, so we get the Management plugin pre-installed.

    docker pull rabbitmq:3.12-management
  4. Now let’s stand it up. We’ll map port 15672 for the management web app and port 5672 for the message broker.

    docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3.12-management

  5. Assuming that ran successfully, you’ve got an instance of RabbitMQ running! Bounce over to http://localhost:15672 to check out the management web app.

You should see a login screen for the RabbitMQ web interface. The default RabbitMQ user name and password is as follows:


username: guest
password: guest


Here you can see an overview of your RabbitMQ instance and the message broker’s basic components: Connections, Channels, Exchanges, and Queues.

Azure Series : Installation - Chocolatey Package Manager

Install Chocolatey Package Manager


What is Chocolatey? 

Chocolatey Official Installation Instructions 

Summary of Installation Steps

  1. RunAsAdministrator - Windows Powershell
  2. From the Powershell prompt install chocolatey using the following command:
    Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
  3. If no errors occurred during installation, you can verify Chocolatey is installed using the following command:
    choco -?