Messaging: queues and pub/sub
Send work to a competing-consumers queue, and broadcast events to a fan-out topic.
What you'll build
A host using SquidStd.Messaging: an IMessageQueue (one consumer handles each message) and an IMessageTopic
(every subscriber receives each message). The same APIs work over RabbitMQ via SquidStd.Messaging.RabbitMq.
Prerequisites
- .NET 10 SDK
dotnet add package SquidStd.Messaging(orSquidStd.Messaging.RabbitMq)
Steps
1. Register in-memory messaging
bootstrap.ConfigureServices(container => container.RegisterCoreServices().AddInMemoryMessaging());
2. Queue: competing consumers
Subscribe a listener and PublishAsync to a named queue. Each message is handled by exactly one consumer.
var queue = bootstrap.Resolve<IMessageQueue>();
using (queue.Subscribe("orders", new OrderListener()))
{
await queue.PublishAsync("orders", new OrderPlaced("order-1"));
await Task.Delay(200);
}
3. Topic: fan-out pub/sub
A topic delivers each published message to every current subscriber.
var topic = bootstrap.Resolve<IMessageTopic>();
using (topic.Subscribe<OrderPlaced>(
"order-events",
(order, _) =>
{
Console.WriteLine($"topic saw {order.Id}");
return Task.CompletedTask;
}
))
{
await topic.PublishAsync("order-events", new OrderPlaced("order-2"));
await Task.Delay(200);
}
Run it
dotnet run --project samples/SquidStd.Samples.Messaging
Prints queue handled order-1 and topic saw order-2.
How it works
Queues use competing-consumers with retry and dead-lettering (MessagingOptions); topics use transient fan-out
(at-most-once). Swap AddInMemoryMessaging() for AddRabbitMqMessaging(...) for a durable broker - the
IMessageQueue/IMessageTopic code is unchanged.