Connect to RabbitMQ
Dette indhold er ikke tilgængeligt i dit sprog endnu.
This page describes how consuming apps connect to a RabbitMQ resource that’s already modeled in your AppHost. For the AppHost API surface — adding a RabbitMQ server, data volumes, management plugin, parameters, and more — see RabbitMQ Hosting integration.
When you reference a RabbitMQ 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 RabbitMQ 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 messaging becomes MESSAGING_URI.
The RabbitMQ server resource exposes the following connection properties:
| Property Name | Description |
|---|---|
Host | The hostname or IP address of the RabbitMQ server |
Port | The port number the RabbitMQ server is listening on |
Username | The username for authentication |
Password | The password for authentication |
VirtualHost | The virtual host path. Defaults to / (the default virtual host). Embedded as the path component of the connection URI when non-default. |
Uri | The connection URI, with the format amqp://{Username}:{Password}@{Host}:{Port} |
Example connection string:
Uri: amqp://guest:p%40ssw0rd1@localhost:5672Connect 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 RabbitMQ resource named messaging and references it from the consuming app.
For C# apps, the recommended approach is the Aspire RabbitMQ client integration. It registers an IConnection 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.RabbitMQ.Client NuGet package in the client-consuming project:
dotnet add package Aspire.RabbitMQ.Client#:package Aspire.RabbitMQ.Client@*<PackageReference Include="Aspire.RabbitMQ.Client" Version="*" />Add the RabbitMQ client
Section titled “Add the RabbitMQ client”In Program.cs, call AddRabbitMQClient on your IHostApplicationBuilder to register an IConnection:
builder.AddRabbitMQClient(connectionName: "messaging");Resolve the connection through dependency injection:
public class ExampleService(IConnection connection){ // Use connection...}Add keyed RabbitMQ clients
Section titled “Add keyed RabbitMQ clients”To register multiple IConnection instances with different connection names, use AddKeyedRabbitMQClient:
builder.AddKeyedRabbitMQClient(name: "chat");builder.AddKeyedRabbitMQClient(name: "queue");Then resolve each instance by key:
public class ExampleService( [FromKeyedServices("chat")] IConnection chatConnection, [FromKeyedServices("queue")] IConnection queueConnection){ // Use connections...}For more information, see .NET dependency injection: Keyed services.
Configuration
Section titled “Configuration”The Aspire RabbitMQ 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 AddRabbitMQClient:
builder.AddRabbitMQClient("messaging");The connection string is resolved from the ConnectionStrings section:
{ "ConnectionStrings": { "messaging": "amqp://username:password@localhost:5672" }}For more information on how to format this connection string, see the RabbitMQ URI specification.
Configuration providers. The client integration supports Microsoft.Extensions.Configuration. It loads RabbitMQClientSettings from appsettings.json (or any other configuration source) by using the Aspire:RabbitMQ:Client key:
{ "Aspire": { "RabbitMQ": { "Client": { "ConnectionString": "amqp://username:password@localhost:5672", "DisableHealthChecks": false, "DisableTracing": false, "MaxConnectRetryCount": 2 } } }}For the complete JSON schema, see Aspire.RabbitMQ.Client/ConfigurationSchema.json.
Inline delegates. Pass an Action<RabbitMQClientSettings> to configure settings inline, for example to disable health checks:
builder.AddRabbitMQClient( "messaging", static settings => settings.DisableHealthChecks = true);You can also configure the IConnectionFactory inline using the configureConnectionFactory delegate parameter:
builder.AddRabbitMQClient( "messaging", configureConnectionFactory: static factory => factory.ClientProvidedName = "MyApp");Auto activation
Section titled “Auto activation”Auto activation opens the RabbitMQ connection during startup rather than lazily on first use, ensuring that any connectivity issues are detected early.
Auto activation is disabled by default in Aspire 9.5 to maintain backward compatibility. To enable it, set DisableAutoActivation to false:
builder.AddRabbitMQClient("messaging", o => o.DisableAutoActivation = false);Client integration health checks
Section titled “Client integration health checks”Aspire client integrations enable health checks by default. The RabbitMQ client integration:
- Adds a health check that attempts to connect to and create a channel on the RabbitMQ server when
DisableHealthChecksisfalse. - Integrates with the
/healthHTTP 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 RabbitMQ client integration automatically configures logging, tracing, and metrics through OpenTelemetry.
Logging categories:
RabbitMQ.Client
Tracing activities:
Aspire.RabbitMQ.Client
Metrics: The RabbitMQ client integration doesn’t currently support metrics by default.
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 📦 RabbitMQ.Client library:
using RabbitMQ.Client;
var uri = new Uri(Environment.GetEnvironmentVariable("MESSAGING_URI")!);var factory = new ConnectionFactory { Uri = uri };
using var connection = await factory.CreateConnectionAsync();using var channel = await connection.CreateChannelAsync();// Use channel to publish or consume messages...Use rabbitmq/amqp091-go, the official Go client for AMQP 0-9-1:
go get github.com/rabbitmq/amqp091-goRead the injected environment variable and connect:
package main
import ( "os" amqp "github.com/rabbitmq/amqp091-go")
func main() { // Read the Aspire-injected connection URI conn, err := amqp.Dial(os.Getenv("MESSAGING_URI")) if err != nil { panic(err) } defer conn.Close()
ch, err := conn.Channel() if err != nil { panic(err) } defer ch.Close()
// Use ch to publish or consume messages...}Install pika, the pure-Python AMQP 0-9-1 client:
pip install pikaRead the injected environment variable and connect:
import osimport pika
# Read the Aspire-injected connection URIparams = pika.URLParameters(os.getenv("MESSAGING_URI"))connection = pika.BlockingConnection(params)channel = connection.channel()
# Use channel to publish or consume messages...connection.close()Install amqplib, the most widely used AMQP 0-9-1 client for Node.js:
npm install amqplibnpm install --save-dev @types/amqplibRead the injected environment variables and connect:
import amqp from 'amqplib';
// Read Aspire-injected connection URIconst connection = await amqp.connect(process.env.MESSAGING_URI!);const channel = await connection.createChannel();
// Use channel to publish or consume messages...await channel.close();await connection.close();Or, build the connection options from individual properties:
import amqp from 'amqplib';
const connection = await amqp.connect({ hostname: process.env.MESSAGING_HOST, port: Number(process.env.MESSAGING_PORT), username: process.env.MESSAGING_USERNAME, password: process.env.MESSAGING_PASSWORD, vhost: process.env.MESSAGING_VIRTUALHOST ?? '/',});