Skip to main content

RabbitMQ tutorial - Publish/Subscribe

Publish/Subscribe​

(using the AMQP 1.0 .NET client)​

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.

In the previous tutorial we created a work queue. In this tutorial we'll deliver a message to multiple consumers — the "publish/subscribe" pattern.

We'll build a simple logging system: one program emits logs, and one or more receivers print them.

Exchanges​

The producer sends messages to an exchange, not directly to a queue. The exchange routes messages to queues according to its type.

Declare a fanout exchange named logs:

IExchangeSpecification exchangeSpec = management.Exchange(exchangeName).Type("fanout");
await exchangeSpec.DeclareAsync();

Bindings​

Bind a temporary exclusive queue to the exchange:

IQueueSpecification tempQueue = management.Queue().Exclusive(true).AutoDelete(true);
IQueueInfo queueInfo = await tempQueue.DeclareAsync();
string queueName = queueInfo.Name();

IBindingSpecification binding = management.Binding()
.SourceExchange(exchangeSpec)
.DestinationQueue(queueName)
.Key(string.Empty);
await binding.BindAsync();

The publisher uses PublisherBuilder().Exchange(exchangeName); the consumer subscribes on queueName and calls ctx.Accept() in the handler.

Running​

From dotnet-amqp:

dotnet run --project ReceiveLogs/ReceiveLogs.csproj
dotnet run --project EmitLog/EmitLog.csproj

Source​

Now we can move on to tutorial 4 and learn how to route messages based on routing keys.