Ir al contenido

NATS integration

Esta página aún no está disponible en tu idioma.

NATS logo

NATS is a simple, secure and high-performance open-source messaging system for cloud-native applications, IoT messaging, and microservices architectures. The Aspire NATS integration provides a way to connect to existing NATS instances or create new instances from Aspire with the docker.io/library/nats container image.

To get started with the Aspire NATS hosting integration, install the Aspire.Hosting.Nats NuGet package in the app host project.

Aspire CLI — Añadir paquete Aspire.Hosting.Nats
aspire add nats

La CLI de Aspire es interactiva; asegúrate de seleccionar el resultado adecuado cuando se te pida:

Aspire CLI — Ejemplo de salida
Select an integration to add:
> nats (Aspire.Hosting.Nats)
> Other results listed as selectable options...

In your app host project, register and consume a NATS server integration using the AddNats extension method to add the NATS server resource to the builder:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var nats = builder.AddNats("nats");
builder.AddProject<Projects.ExampleProject>()
.WithReference(nats);
// After adding all resources, run the app...

To add NATS with JetStream enabled, which provides streaming capabilities, use the WithJetStream extension method:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var nats = builder.AddNats("nats")
.WithJetStream();
builder.AddProject<Projects.ExampleProject>()
.WithReference(nats);

To add data volumes for persisting NATS data, call the WithDataVolume method:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var nats = builder.AddNats("nats")
.WithJetStream()
.WithDataVolume();
builder.AddProject<Projects.ExampleProject>()
.WithReference(nats);

The data volume is used to persist the NATS data outside the lifecycle of the container.

For development scenarios, you may want to use bind mounts instead of data volumes. To add a data bind mount, call the WithDataBindMount method:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var nats = builder.AddNats("nats")
.WithJetStream()
.WithDataBindMount(source: @"C:\Nats\Data");
builder.AddProject<Projects.ExampleProject>()
.WithReference(nats);

To add NATS with username and password authentication, use the WithNatsUser and WithNatsPassword parameters:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var nats = builder.AddNats("nats", userName: "nats", password: "pass");
builder.AddProject<Projects.ExampleProject>()
.WithReference(nats);

When you reference a NATS resource using WithReference, the following connection properties are made available to the consuming project:

The NATS server resource exposes the following connection properties:

Property NameDescription
HostThe hostname or IP address of the NATS server
PortThe port number the NATS server is listening on
UsernameThe username for authentication
PasswordThe password for authentication
UriThe connection URI with the format nats://{Username}:{Password}@{Host}:{Port}

Example connection string:

Uri: nats://admin:p%40ssw0rd1@localhost:4222

To get started with the Aspire NATS client integration, install the Aspire.NATS.Net NuGet package in the consuming client project:

.NET CLI — Add Aspire.NATS.Net package
dotnet add package Aspire.NATS.Net

In the Program.cs file of your client-consuming project, call the AddNatsClient extension method to register an INatsConnection for use through dependency injection. The method takes a connection name parameter:

builder.AddNatsClient(connectionName: "nats");

You can then retrieve the INatsConnection instance using dependency injection. For example, to retrieve the connection object from an example service:

public class ExampleService(INatsConnection connection)
{
// Use connection...
}

There might be situations where you want to register multiple INatsConnection instances with different connection names. To register keyed NATS clients, call the AddKeyedNatsClient method:

builder.AddKeyedNatsClient(name: "products");
builder.AddKeyedNatsClient(name: "orders");

Then you can retrieve the INatsConnection instances using dependency injection. For example, to retrieve the connection from an example service:

public class ExampleService(
[FromKeyedServices("products")] INatsConnection productsConnection,
[FromKeyedServices("orders")] INatsConnection ordersConnection)
{
// Use connections...
}

For more information on keyed services, see .NET dependency injection: Keyed services.

The Aspire NATS client integration provides multiple configuration approaches. You can provide configuration using appsettings.json, configuration keys, or inline code.

The Aspire NATS client integration supports Microsoft.Extensions.Configuration. It loads the NatsClientSettings from configuration using the Aspire:Nats:Client key:

{
"Aspire": {
"Nats": {
"Client": {
"ConnectionString": "nats://localhost:4222",
"DisableHealthChecks": false,
"DisableTracing": false
}
}
}
}

For the complete NATS client integration JSON schema, see Aspire.NATS.Net/ConfigurationSchema.json.

You can also pass the Action<NatsClientSettings> delegate to set up some or all the options inline:

builder.AddNatsClient(
"nats",
static settings => settings.DisableHealthChecks = true);

By default, the Aspire NATS integration handles health checks using the AspNetCore.HealthChecks.Nats package. This integration registers a health check that verifies the connection to the NATS server.

The NATS client integration registers a health check using the connection name. The health check verifies that the connection is active and can be used to send and receive messages.

The Aspire NATS integration emits tracing activities using OpenTelemetry. The integration automatically enables tracing for NATS operations.

The following are the tracing activities emitted by NATS components:

  • “NATS”: Emitted by NatsConnection.
  • “NATS.Net”: Emitted by the NATS .NET client library.

For more information about tracing activities, see NATS .NET client library: OpenTelemetry support.

Preguntas y respuestasColaboraComunidadDebatirVer bajo demanda