Core NATS
Core NATS is the base set of functionalities and qualities of service offered by a NATS service infrastructure. Core NATS is the foundation for JetStream and other services. For the sake of explanation, in a simplified sense you can think of Core NATS as the wire protocol defining a simple but powerful pub/sub functionality and the concept of Subject-Based Messaging.
Quick Start
Download the latest nats-server
for your platform and run it without any arguments. nats-server
will listen
on its default TCP port 4222. You can also use a containerized version of the NATS server:
$ nats-server
or
$ docker run nats
Install NATS.Net from Nuget.
Given that we have a plain class Bar
, we can publish and subscribe to our nats-server
sending
and receiving Bar
objects:
public record Bar(int Id, string Name);
Subscribe to all bar
related subjects:
await using var nc = new NatsClient();
await foreach (var msg in nc.SubscribeAsync<Bar>("bar.>"))
{
if (msg.Subject == "bar.exit")
break;
Console.WriteLine($"Received {msg.Subject}: {msg.Data}\n");
}
Publish Bar
objects to related bar
subjects:
await using var nc = new NatsClient();
for (var i = 0; i < 10; i++)
{
Console.WriteLine($" Publishing {i}...");
await nc.PublishAsync<Bar>($"bar.baz.{i}", new Bar(Id: i, Name: "Baz"));
}
await nc.PublishAsync("bar.exit");
What's Next
Publish-Subscribe is the message distribution model for one-to-many communication.
Request-Reply is a common pattern in modern distributed systems. A request is sent, and the application either waits on the response with a certain timeout, or receives a response asynchronously.
Queue Groups enables the 1:N fan-out pattern of messaging ensuring that any message sent by a publisher, reaches all subscribers that have registered.