Skip to main content

RabbitMQ tutorial - "Hello World!"

Introduction

info

Prerequisites

This tutorial assumes RabbitMQ is installed and running on localhost on the standard port (5672). In case you use a different host, port or credentials, connections settings would require adjusting.

Where to get help

If you're having trouble going through this tutorial you can contact us through GitHub Discussions or RabbitMQ community Discord.

RabbitMQ is a message broker: it accepts and forwards messages. You can think about it as a post office: when you put the mail that you want posting in a post box, you can be sure that the letter carrier will eventually deliver the mail to your recipient. In this analogy, RabbitMQ is a post box, a post office, and a letter carrier.

The major difference between RabbitMQ and the post office is that it doesn't deal with paper, instead it accepts, stores, and forwards binary blobs of data ‒ messages.

RabbitMQ, and messaging in general, uses some jargon.

  • Producing means nothing more than sending. A program that sends messages is a producer :

  • A queue is the name for the post box in RabbitMQ. Although messages flow through RabbitMQ and your applications, they can only be stored inside a queue. A queue is only bound by the host's memory & disk limits, it's essentially a large message buffer.

    Many producers can send messages that go to one queue, and many consumers can try to receive data from one queue.

    This is how we represent a queue:

  • Consuming has a similar meaning to receiving. A consumer is a program that mostly waits to receive messages:

Note that the producer, consumer, and broker do not have to reside on the same host; indeed in most applications they don't. An application can be both a producer and consumer, too.

"Hello World"

(using the AMQP 1.0 .NET client)

In this part of the tutorial we'll write two small programs in C#; a producer that sends a single message, and a consumer that receives messages and prints them out. We'll gloss over some of the detail in the .NET AMQP 1.0 client API, concentrating on this very simple thing just to get started. It's the "Hello World" of messaging.

In the diagram below, "P" is our producer and "C" is our consumer. The box in the middle is a queue - a message buffer that RabbitMQ keeps on behalf of the consumer.

The AMQP 1.0 .NET client library

RabbitMQ speaks multiple protocols. This tutorial uses AMQP 1.0 over the same port as AMQP 0-9-1 (5672 by default). It requires RabbitMQ 4.0 or later.

Use the RabbitMQ AMQP 1.0 .NET client (RabbitMQ.AMQP.Client on NuGet), not the classic AMQP 0-9-1 client (RabbitMQ.Client). See AMQP 1.0 client libraries and the .NET client API.

Add the package to your project:

dotnet add package RabbitMQ.AMQP.Client

Runnable sources for this tutorial series are available in the RabbitMQ tutorials repository (dotnet-amqp directory) once merged upstream.

Now we have the client referenced, we can write some code.

Sending

We'll call our message publisher (sender) Send and our message consumer Receive. The publisher will connect to RabbitMQ, send a single message, then exit.

In Send/Program.cs, use these namespaces:

using System.Text;
using RabbitMQ.AMQP.Client;
using RabbitMQ.AMQP.Client.Impl;

Create connection settings, an environment, and a connection. The URI uses the default virtual host (%2f is /):

const string brokerUri = "amqp://guest:guest@localhost:5672/%2f";

ConnectionSettings settings = ConnectionSettingsBuilder.Create()
.Uri(new Uri(brokerUri))
.ContainerId("tutorial-send")
.Build();

IEnvironment environment = AmqpEnvironment.Create(settings);
IConnection connection = await environment.CreateConnectionAsync();

Declare a quorum queue named hello, then create a publisher and publish a message. Check PublishResult.Outcome.State for OutcomeState.Accepted:

try
{
IManagement management = connection.Management();
IQueueSpecification queueSpec = management.Queue("hello").Type(QueueType.QUORUM);
await queueSpec.DeclareAsync();

IPublisher publisher = await connection.PublisherBuilder().Queue("hello").BuildAsync();
try
{
const string body = "Hello World!";
var message = new AmqpMessage(Encoding.UTF8.GetBytes(body));
PublishResult pr = await publisher.PublishAsync(message);
if (pr.Outcome.State != OutcomeState.Accepted)
{
Console.Error.WriteLine($"Unexpected publish outcome: {pr.Outcome.State}");
Environment.Exit(1);
}

Console.WriteLine($" [x] Sent {body}");
}
finally
{
await publisher.CloseAsync();
}
}
finally
{
await connection.CloseAsync();
await environment.CloseAsync();
}

Full Send/Program.cs source (once merged upstream).

Sending doesn't work!

If this is your first time using RabbitMQ and you don't see the " [x] Sent" message then you may be left scratching your head wondering what could be wrong. Maybe the broker was started without enough free disk space (by default it needs at least 50 MB free) and is therefore refusing to accept messages. Check the broker log file to see if there is a resource alarm logged.

Receiving

That's it for our publisher. Our consumer listens for messages from RabbitMQ, so unlike the publisher which publishes a single message, we'll keep the consumer running to listen for messages and print them out.

The code in Receive/Program.cs declares the same quorum queue, then builds a consumer with a message handler. Call ctx.Accept() to settle the message (AMQP 1.0):

IManagement management = connection.Management();
IQueueSpecification queueSpec = management.Queue("hello").Type(QueueType.QUORUM);
await queueSpec.DeclareAsync();

IConsumer consumer = await connection.ConsumerBuilder()
.Queue("hello")
.MessageHandler((ctx, message) =>
{
Console.WriteLine($"Received a message: {Encoding.UTF8.GetString(message.Body()!)}");
ctx.Accept();
return Task.CompletedTask;
})
.BuildAndStartAsync();

Use Ctrl+C handling and Task.Delay(Timeout.Infinite, cts.Token) to keep the process alive until interrupted.

Full Receive/Program.cs source (once merged upstream).

Putting it all together

From the dotnet-amqp directory, run the consumer then the publisher:

dotnet run --project Receive/Receive.csproj
dotnet run --project Send/Send.csproj

The consumer will print the message it gets from the publisher via RabbitMQ.

Listing queues

You may wish to see what queues RabbitMQ has and how many messages are in them. You can do it (as a privileged user) using the rabbitmqctl tool:

sudo rabbitmqctl list_queues

On Windows, omit the sudo:

rabbitmqctl.bat list_queues

Time to move on to part 2 and build a simple work queue.