RabbitMQ Messaging for .NET 8 Web API with Windows Client Part 2

After Building the existing WebApi, as mentioned in the previous article. Now, I will explain to you how this message can be reached to the Client app.

First, run the WebApi on your local computer using Visual Studio.

How to know the application is running?

Just check the WebApi .exe file is running in the system tray or task Manager.

Application is running

As it is using the development environment to test the api, I am using the Swagger tool, which is built into the web APIbapi application.

Swagger

Open the existing Project solution in Visual Studio.

Queue

Add another Console application Project into the solution, Or it may be a different project.

Solution explorer

Open the Program.cs file, add the below code snippet into the application.

namespace RabbitMQProduct.ConsoleApplication
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Specify the connection factory for RabbitMQ
            var factory = new ConnectionFactory
            {
                HostName = "localhost"
            };
            // Create a connection to RabbitMQ
            var connection = factory.CreateConnection();
            // Create a channel
            using var channel = connection.CreateModel();
            // Declare a queue
            channel.QueueDeclare(queue: "ProductQueue", durable: false, exclusive: false, autoDelete: false);
            // Create a consumer
            var consumer = new EventingBasicConsumer(channel);
            // Register the consumer 
            consumer.Received += (model, eventArgs) => {
                // Consume the message
                var body = eventArgs.Body.ToArray();
                var message = Encoding.UTF8.GetString(body);
                Console.WriteLine($"Product message received: {message}");
            };
            // Consume the message
            channel.BasicConsume(queue: "ProductQueue", autoAck: true, consumer: consumer);
            // Wait for the user to press a key
            Console.ReadKey();
        }
    }
}

Explain the above code snippet.

First, create the Connection Factory for the RabbitMQ broker.

var factory = new ConnectionFactory
{
    HostName = "localhost"
};

Second, now creating the connection with RabbitMQ

var connection = factory.CreateConnection();

The connection requires a path to access the resource from Rabbit, which is nothing but a channel. It acts as a Model ( it returns fresh Channel, Session & model), and also uses "USING" which is used to ensure that the object is disposed of correctly after it is completed. So it will not go through any exceptions.

using var channel = connection.CreateModel();

Now I need to declare a queue from Rabbit.

channel.QueueDeclare(queue: "ProductQueue", durable: false, exclusive: false, autoDelete: false);

Here in the main RabbitMQProductApi, it can host multiple queues, so consumers don't know which one needs to select from the queue that is hosted for this application.

RabbitMQProductApi/RabbitMQProducer.cs

namespace RabbitMQProductApi.RabbitMQ
{
    public class RabbitMQProducer : IRabbitMQProducer
    {
        public void SendProductMessage<T>(T message)
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };
            var connection = factory.CreateConnection();
            var channel = connection.CreateModel();
            channel.QueueDeclare(queue: "ProductQueue", durable: false, exclusive: false, autoDelete: false, arguments: null);
            var json = System.Text.Json.JsonSerializer.Serialize(message);
            var body = System.Text.Encoding.UTF8.GetBytes(json);
            channel.BasicPublish(exchange: "", routingKey: "ProductQueue", basicProperties: null, body: body);
        }
    }
}

See Host Application Queue name should be the same when it is consumed in other applications.

Here it is "ProductQueue".

Now check it On the RabbitMQ web page, with queue details, and find the "ProductQueue"

Rabbit MQ

Here, we can see that the host application sends the value to the rabbitMQ broker, and then the consuming application can get the value without any notification to other applications. The customer has already subscribed to the queue which is specified below.

In the API, I just add the value it is added into the DB, and then it is broadcasted into RabbitMQ, So the console application with receive the added value from the broker.

Response

Thank you