編輯

共用方式為


.NET Aspire RabbitMQ integration

Includes: Hosting integration and Client integration

RabbitMQ is a reliable messaging and streaming broker, which is easy to deploy on cloud environments, on-premises, and on your local machine. The .NET Aspire RabbitMQ integration enables you to connect to existing RabbitMQ instances, or create new instances from .NET with the docker.io/library/rabbitmq container image.

Hosting integration

The RabbitMQ hosting integration models a RabbitMQ server as the RabbitMQServerResource type. To access this type and APIs that allow you to add it to your app model, install the 📦 Aspire.Hosting.RabbitMQ NuGet package in the app host project.

dotnet add package Aspire.Hosting.RabbitMQ

For more information, see dotnet add package or Manage package dependencies in .NET applications.

Add RabbitMQ server resource

In your app host project, call AddRabbitMQ on the builder instance to add a RabbitMQ server resource:

var builder = DistributedApplication.CreateBuilder(args);

var rabbitmq = builder.AddRabbitMQ("messaging");

builder.AddProject<Projects.ExampleProject>()
       .WithReference(rabbitmq);

// After adding all resources, run the app...

When .NET Aspire adds a container image to the app host, as shown in the preceding example with the docker.io/library/rabbitmq image, it creates a new RabbitMQ server instance on your local machine. A reference to your RabbitMQ server (the rabbitmq variable) is added to the ExampleProject. The RabbitMQ server resource includes default credentials with a username of "guest" and randomly generated password using the CreateDefaultPasswordParameter method.

The WithReference method configures a connection in the ExampleProject named "messaging". For more information, see Container resource lifecycle.

Tip

If you'd rather connect to an existing RabbitMQ server, call AddConnectionString instead. For more information, see Reference existing resources.

Add RabbitMQ server resource with management plugin

To add the RabbitMQ management plugin to the RabbitMQ server resource, call the WithManagementPlugin method:

var builder = DistributedApplication.CreateBuilder(args);

var rabbitmq = builder.AddRabbitMQ("messaging")
                      .WithManagementPlugin();

builder.AddProject<Projects.ExampleProject>()
        .WithReference(rabbitmq);

// After adding all resources, run the app...

The RabbitMQ management plugin provides an HTTP-based API for management and monitoring of your RabbitMQ server. .NET Aspire adds another container image docker.io/library/rabbitmq-management to the app host that runs the management plugin.

Add RabbitMQ server resource with data volume

To add a data volume to the RabbitMQ server resource, call the WithDataVolume method on the RabbitMQ server resource:

var builder = DistributedApplication.CreateBuilder(args);

var rabbitmq = builder.AddRabbitMQ("messaging")
                      .WithDataVolume(isReadOnly: false);

builder.AddProject<Projects.ExampleProject>()
        .WithReference(rabbitmq);

// After adding all resources, run the app...

The data volume is used to persist the RabbitMQ server data outside the lifecycle of its container. The data volume is mounted at the /var/lib/rabbitmq path in the RabbitMQ server container and when a name parameter isn't provided, the name is generated at random. For more information on data volumes and details on why they're preferred over bind mounts, see Docker docs: Volumes.

Add RabbitMQ server resource with data bind mount

To add a data bind mount to the RabbitMQ server resource, call the WithDataBindMount method:

var builder = DistributedApplication.CreateBuilder(args);

var rabbitmq = builder.AddRabbitMQ("messaging")
                      .WithDataBindMount(
                          source: @"C:\RabbitMQ\Data",
                          isReadOnly: false);

builder.AddProject<Projects.ExampleProject>()
        .WithReference(rabbitmq);

// After adding all resources, run the app...

Tip

Data bind mounts have limited functionality compared to volumes, which offer better performance, portability, and security, making them more suitable for production environments. However, bind mounts allow direct access and modification of files on the host system, ideal for development and testing where real-time changes are needed.

Data bind mounts rely on the host machine's filesystem to persist the RabbitMQ server data across container restarts. The data bind mount is mounted at the C:\RabbitMQ\Data on Windows (or /RabbitMQ/Data on Unix) path on the host machine in the RabbitMQ server container. For more information on data bind mounts, see Docker docs: Bind mounts.

Add RabbitMQ server resource with parameters

When you want to explicitly provide the username and password used by the container image, you can provide these credentials as parameters. Consider the following alternative example:

var builder = DistributedApplication.CreateBuilder(args);

var username = builder.AddParameter("username", secret: true);
var password = builder.AddParameter("password", secret: true);

var rabbitmq = builder.AddRabbitMQ("messaging", username, password);

builder.AddProject<Projects.ExampleProject>()
       .WithReference(rabbitmq);

// After adding all resources, run the app...

For more information on providing parameters, see External parameters.

Hosting integration health checks

The RabbitMQ hosting integration automatically adds a health check for the RabbitMQ server resource. The health check verifies that the RabbitMQ server is running and that a connection can be established to it.

The hosting integration relies on the 📦 AspNetCore.HealthChecks.Rabbitmq NuGet package.

Client integration

To get started with the .NET Aspire RabbitMQ client integration, install the 📦 Aspire.RabbitMQ.Client NuGet package in the client-consuming project, that is, the project for the application that uses the RabbitMQ client. The RabbitMQ client integration registers an IConnection instance that you can use to interact with RabbitMQ.

dotnet add package Aspire.RabbitMQ.Client

Add RabbitMQ client

In the Program.cs file of your client-consuming project, call the AddRabbitMQClient extension method on any IHostApplicationBuilder to register an IConnection for use via the dependency injection container. The method takes a connection name parameter.

builder.AddRabbitMQClient(connectionName: "messaging");

Tip

The connectionName parameter must match the name used when adding the RabbitMQ server resource in the app host project. For more information, see Add RabbitMQ server resource.

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

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

For more information on dependency injection, see .NET dependency injection.

Add keyed RabbitMQ client

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

builder.AddKeyedRabbitMQClient(name: "chat");
builder.AddKeyedRabbitMQClient(name: "queue");

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

public class ExampleService(
    [FromKeyedServices("chat")] IConnection chatConnection,
    [FromKeyedServices("queue")] IConnection queueConnection)
{
    // Use connections...
}

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

Configuration

The .NET Aspire RabbitMQ integration provides multiple options to configure the connection based on the requirements and conventions of your project.

Use a connection string

When using a connection string from the ConnectionStrings configuration section, you can provide the name of the connection string when calling builder.AddRabbitMQClient:

builder.AddRabbitMQClient(connectionName: "messaging");

Then the connection string is retrieved from the ConnectionStrings configuration section:

{
  "ConnectionStrings": {
    "messaging": "amqp://username:password@localhost:5672"
  }
}

For more information on how to format this connection string, see the RabbitMQ URI specification docs.

Use configuration providers

The .NET Aspire RabbitMQ integration supports Microsoft.Extensions.Configuration. It loads the RabbitMQClientSettings from configuration by using the Aspire:RabbitMQ:Client key. The following snippet is an example of a appsettings.json file that configures some of the options:

{
  "Aspire": {
    "RabbitMQ": {
      "Client": {
        "ConnectionString": "amqp://username:password@localhost:5672",
        "DisableHealthChecks": true,
        "DisableTracing": true,
        "MaxConnectRetryCount": 2
      }
    }
  }
}

For the complete RabbitMQ client integration JSON schema, see Aspire.RabbitMQ.Client/ConfigurationSchema.json.

Use inline delegates

Also you can pass the Action<RabbitMQClientSettings> configureSettings delegate to set up some or all the options inline, for example to disable health checks from code:

builder.AddRabbitMQClient(
    "messaging",
    static settings => settings.DisableHealthChecks = true);

You can also set up the IConnectionFactory using the Action<IConnectionFactory> configureConnectionFactory delegate parameter of the AddRabbitMQClient method. For example to set the client provided name for connections:

builder.AddRabbitMQClient(
    "messaging",
    configureConnectionFactory:
        static factory => factory.ClientProvidedName = "MyApp");

Client integration health checks

By default, .NET Aspire integrations enable health checks for all services. For more information, see .NET Aspire integrations overview.

The .NET Aspire RabbitMQ integration:

  • Adds the health check when RabbitMQClientSettings.DisableHealthChecks is false, which attempts to connect to and create a channel on the RabbitMQ server.
  • Integrates with the /health HTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic.

Observability and telemetry

.NET Aspire integrations automatically set up Logging, Tracing, and Metrics configurations, which are sometimes known as the pillars of observability. For more information about integration observability and telemetry, see .NET Aspire integrations overview. Depending on the backing service, some integrations might only support some of these features. For example, some integrations support logging and tracing, but not metrics. Telemetry features can also be disabled using the techniques presented in the Configuration section.

Logging

The .NET Aspire RabbitMQ integration uses the following log categories:

  • RabbitMQ.Client

Tracing

The .NET Aspire RabbitMQ integration emits the following tracing activities using OpenTelemetry:

  • Aspire.RabbitMQ.Client

Metrics

The .NET Aspire RabbitMQ integration currently doesn't support metrics by default.

See also