Connect to NATS
Esta página aún no está disponible en tu idioma.
This page describes how consuming apps connect to a NATS resource that’s already modeled in your AppHost. For the AppHost API surface — adding a NATS resource, JetStream, data volumes, parameters, and more — see NATS Hosting integration.
When you reference a NATS resource from your AppHost, Aspire injects the connection information into the consuming app as environment variables. Your app can either read those environment variables directly — the pattern works the same from any language — or, in C#, use the Aspire NATS client integration for automatic dependency injection, health checks, and telemetry.
Connection properties
Section titled “Connection properties”Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called nats becomes NATS_URI.
The NATS resource exposes the following connection properties:
| Property Name | Description |
|---|---|
Host | The hostname or IP address of the NATS server |
Port | The port number the NATS server is listening on |
Username | The username for authentication |
Password | The password for authentication |
Uri | The connection URI, with the format nats://{Username}:{Password}@{Host}:{Port} |
Example connection string:
Uri: nats://admin:p%40ssw0rd1@localhost:4222Connect from your app
Section titled “Connect from your app”Pick the language your consuming app is written in. Each example assumes your AppHost adds a NATS resource named nats and references it from the consuming app.
For C# apps, the recommended approach is the Aspire NATS client integration. It registers an INatsConnection through dependency injection and adds health checks and telemetry automatically. If you’d rather read environment variables directly, see the Read environment variables section at the end of this tab.
Install the client integration
Section titled “Install the client integration”Install the 📦 Aspire.NATS.Net NuGet package in the client-consuming project:
dotnet add package Aspire.NATS.Net#:package Aspire.NATS.Net@*<PackageReference Include="Aspire.NATS.Net" Version="*" />Add the NATS client
Section titled “Add the NATS client”In Program.cs, call AddNatsClient on your IHostApplicationBuilder to register an INatsConnection:
builder.AddNatsClient(connectionName: "nats");Resolve the connection through dependency injection:
public class ExampleService(INatsConnection connection){ // Use connection...}Add keyed NATS clients
Section titled “Add keyed NATS clients”To register multiple INatsConnection instances with different connection names, use AddKeyedNatsClient:
builder.AddKeyedNatsClient(name: "products");builder.AddKeyedNatsClient(name: "orders");Then resolve each instance by key:
public class ExampleService( [FromKeyedServices("products")] INatsConnection productsConnection, [FromKeyedServices("orders")] INatsConnection ordersConnection){ // Use connections...}For more information, see .NET dependency injection: Keyed services.
Configuration
Section titled “Configuration”The Aspire NATS client integration offers multiple ways to provide configuration.
Connection strings. When using a connection string from the ConnectionStrings configuration section, pass the connection name to AddNatsClient:
builder.AddNatsClient("nats");The connection string is resolved from the ConnectionStrings section:
{ "ConnectionStrings": { "nats": "nats://localhost:4222" }}Configuration providers. The client integration supports Microsoft.Extensions.Configuration. It loads NatsClientSettings from appsettings.json (or any other configuration source) by 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.
Inline delegates. Pass an Action<NatsClientSettings> to configure settings inline, for example to disable health checks:
builder.AddNatsClient( "nats", static settings => settings.DisableHealthChecks = true);Client integration health checks
Section titled “Client integration health checks”Aspire client integrations enable health checks by default. The NATS client integration adds a health check that verifies the NATS instance is reachable and can execute commands. The health check is wired into the /health HTTP endpoint, where all registered health checks must pass before the app is considered ready to accept traffic.
Observability and telemetry
Section titled “Observability and telemetry”The Aspire NATS client integration automatically configures tracing through OpenTelemetry.
Tracing activities:
NATS— emitted byNatsConnectionNATS.Net— emitted by the NATS .NET client library
For more information about tracing activities, see NATS .NET client library: OpenTelemetry support.
Any of these telemetry features can be disabled through the configuration options above.
Read environment variables in C#
Section titled “Read environment variables in C#”If you prefer not to use the Aspire client integration, you can read the Aspire-injected connection URI from the environment and pass it directly to the 📦 NATS.Net NuGet package:
using NATS.Client.Core;
var connectionUri = Environment.GetEnvironmentVariable("NATS_URI");
await using var connection = new NatsConnection( NatsOpts.Default with { Url = connectionUri! });
await connection.ConnectAsync();// Use connection...Use the official nats.go client:
go get github.com/nats-io/nats.goRead the injected environment variable and connect:
package main
import ( "os" "github.com/nats-io/nats.go")
func main() { // Read the Aspire-injected connection URI natsURI := os.Getenv("NATS_URI")
nc, err := nats.Connect(natsURI) if err != nil { panic(err) } defer nc.Close()
// Use nc to publish and subscribe...}Install nats-py, the official Python NATS client:
pip install nats-pyRead the injected environment variable and connect:
import asyncioimport osimport nats
async def main(): # Read the Aspire-injected connection URI nats_uri = os.getenv("NATS_URI")
nc = await nats.connect(nats_uri) # Use nc to publish and subscribe... await nc.close()
asyncio.run(main())Install the nats package (@nats-io/nats-core):
npm install natsRead the injected environment variables and connect:
import { connect } from 'nats';
// Read the Aspire-injected connection URIconst nc = await connect({ servers: process.env.NATS_URI,});
// Use nc to publish and subscribe...await nc.drain();Or use individual connection properties:
import { connect } from 'nats';
const nc = await connect({ servers: `${process.env.NATS_HOST}:${process.env.NATS_PORT}`, user: process.env.NATS_USERNAME, pass: process.env.NATS_PASSWORD,});