Publish-Subscribe Pattern
NATS implements a publish-subscribe message distribution model for one-to-many communication. A publisher sends a message on a subject and any active subscriber listening on that subject receives the message.
await using NatsClient nc = new NatsClient();
Task subscription = Task.Run(async () =>
{
await foreach (NatsMsg<int> msg in nc.SubscribeAsync<int>("foo"))
{
Console.WriteLine($"Received {msg.Subject}: {msg.Data}\n");
if (msg.Data == -1)
break;
}
});
// Give subscription time to start
await Task.Delay(1000);
for (int i = 0; i < 10; i++)
{
Console.WriteLine($" Publishing {i}...");
await nc.PublishAsync<int>("foo", i);
}
// Signal subscription to stop
await nc.PublishAsync<int>("foo", -1);
// Make sure subscription completes cleanly
await subscription;
You can run multiple subscribers to the same subject, and each subscriber will receive a copy of the message. At the same time, you can have multiple publishers sending messages to the same subject. This is a powerful feature of NATS that enables many messaging patterns.