SETTING UP A DIRECT QUEUE IN RABBITMQ

What is a direct queue?

A direct queue is the simplest form, where one sender sends a message directly to one receiver.
A direct queue will use the Routing Key to connect the sender and receiver.
There is no need to set up an Exchange because the system will use a default one.
You can of course set up many direct queues, as long as they all have unique Routing Keys.

For more info about the different queues, look here: All RabbitMQ Articles

NuGet

To set up a RabbitMQ client you only need one NuGet package.

The code

This is basically what is needed to create a direct queue. You do this in both the sending and receiving clients.

private IAsyncConnectionFactory _factory;
private IConnection? _connection;
private IModel? _channel;

public void CreateQueue()
{
    _factory =
        new ConnectionFactory
        {
            HostName = "localhost",
            UserName = "guest",
            Password = "guest",
        };

    _connection = _factory.CreateConnection();
    _channel = _connection.CreateModel();

    _channel.QueueDeclare(
        "DirectQueue", 
        durable: true,
        exclusive: false,
        autoDelete: false,
        arguments: null);
}

The code explained

_factory =
    new ConnectionFactory
    {
        HostName = "localhost",
        UserName = "guest",
        Password = "guest",
    };

The factory is where all entities that RabbitMQ uses are created.
It is also here you tell the client where the RabbitMQ server is, and what account to use.

HostNameThe IP address to the RabbitMQ server.
UserNameThe name of the user that is used to gain access to the server.
PasswordThe password that verifies the user.

The default user name and password is guest/ guest.

_connection = _factory.CreateConnection();

This is basically the TCP connection to the server. This is where all the queues will be sending its data. Since it is created from the factory, it knows what server to create a connection to.

_channel = _connection.CreateModel();

From the RabbitMQ documentation
https://www.rabbitmq.com/channels.html

Some applications need multiple logical connections to the broker. However, it is undesirable to keep many TCP connections open at the same time because doing so consumes system resources and makes it more difficult to configure firewalls. AMQP 0-9-1 connections are multiplexed with channels that can be thought of as “lightweight connections that share a single TCP connection”.

https://www.rabbitmq.com/channels.html#basics
_channel.QueueDeclare(
        "DirectQueue",
        durable: true,
        exclusive: false,
        autoDelete: false,
        arguments: null);

This is where the queue is created. Doing it like this creates a direct queue. To send messages, use the queue name “DirectQueue” to tell the system what queue to use.

— Cheers!

Like it? Share it!

Leave a Reply

Your email address will not be published. Required fields are marked *