İçeriğe geç
Docs Try Aspire
Docs Try

Connect to Azure Cache for Redis

Bu içerik henüz dilinizde mevcut değil.

Azure Cache for Redis logo

This page describes how consuming apps connect to an Azure Cache for Redis resource that’s already modeled in your AppHost. For the AppHost API surface — adding a managed Redis resource, running as a local container, Entra ID versus access key authentication, and more — see Azure Cache for Redis Hosting integration.

When you reference an Azure Cache for Redis 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 Redis client integration for automatic dependency injection, health checks, and telemetry.

Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called cache becomes CACHE_URI.

The Azure Managed Redis resource exposes the following connection properties:

Property NameDescription
HostThe hostname of the Azure Cache for Redis endpoint
PortThe port number. Uses the default Azure Cache for Redis TLS port when connecting to Azure; uses the configured container port when running locally via RunAsContainer
PasswordThe access key. Empty when using Entra ID authentication; populated when using WithAccessKeyAuthentication or running as a local container
UriThe connection URI. In Azure mode: redis://{Host}; when running as a local container: redis://[:{Password}@]{Host}:{Port}

Example connection strings:

Uri (Azure mode, Entra ID): redis://myredis.redis.cache.windows.net
Uri (local container mode): redis://:p%40ssw0rd1@localhost:6379

Pick the language your consuming app is written in. Each example assumes your AppHost adds an Azure Managed Redis resource named cache and references it from the consuming app.

For C# apps, the recommended approach is the Aspire Redis client integration. It registers an IConnectionMultiplexer through dependency injection and adds health checks and telemetry automatically. If you’d rather read environment variables directly, see the Read environment variables in C# section at the end of this tab.

Install the 📦 Aspire.StackExchange.Redis NuGet package in the client-consuming project:

.NET CLI — Add Aspire.StackExchange.Redis package
dotnet add package Aspire.StackExchange.Redis

In Program.cs, call AddRedisClient on your IHostApplicationBuilder to register an IConnectionMultiplexer:

C# — Program.cs
builder.AddRedisClient(connectionName: "cache");

Resolve the connection multiplexer through dependency injection:

C# — ExampleService.cs
public class ExampleService(IConnectionMultiplexer connectionMux)
{
// Use connection multiplexer...
}

To register multiple IConnectionMultiplexer instances with different connection names, use AddKeyedRedisClient:

C# — Program.cs
builder.AddKeyedRedisClient(name: "primary-cache");
builder.AddKeyedRedisClient(name: "secondary-cache");

Then resolve each instance by key:

C# — ExampleService.cs
public class ExampleService(
[FromKeyedServices("primary-cache")] IConnectionMultiplexer primaryMux,
[FromKeyedServices("secondary-cache")] IConnectionMultiplexer secondaryMux)
{
// Use connections...
}

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

To enable Microsoft Entra ID (managed identity) authentication for Azure Cache for Redis in C#, install the 📦 Aspire.Microsoft.Azure.StackExchangeRedis NuGet package and use the AddRedisClientBuilder API with WithAzureAuthentication:

C# — Program.cs
builder.AddRedisClientBuilder("cache")
.WithAzureAuthentication();

This configures the Redis client to obtain access tokens using the app’s managed identity when running in Azure, without storing passwords in connection strings.

The Aspire Redis 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 AddRedisClient:

C# — Program.cs
builder.AddRedisClient("cache");

The connection string is resolved from the ConnectionStrings section:

JSON — appsettings.json
{
"ConnectionStrings": {
"cache": "myredis.redis.cache.windows.net:6380,ssl=True,password=..."
}
}

For more information, see Stack Exchange Redis configuration.

Configuration providers. The client integration supports Microsoft.Extensions.Configuration. It loads StackExchangeRedisSettings from appsettings.json (or any other configuration source) by using the Aspire:StackExchange:Redis key:

JSON — appsettings.json
{
"Aspire": {
"StackExchange": {
"Redis": {
"ConnectionString": "myredis.redis.cache.windows.net:6380,ssl=True",
"DisableHealthChecks": false,
"DisableTracing": false
}
}
}
}

Inline delegates. Pass an Action<StackExchangeRedisSettings> to configure settings inline, for example to disable tracing:

C# — Program.cs
builder.AddRedisClient(
"cache",
static settings => settings.DisableTracing = true);

Aspire client integrations enable health checks by default. The Redis client integration adds a health check that verifies the Redis 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.

The Aspire Redis client integration automatically configures logging, tracing, and metrics through OpenTelemetry.

Logging categories:

  • Aspire.StackExchange.Redis

Tracing activities:

  • OpenTelemetry.Instrumentation.StackExchangeRedis

Metrics are emitted through OpenTelemetry. Any of these telemetry features can be disabled through the configuration options above.

Azure Cache for Redis also works with the Aspire distributed-caching and output-caching client integrations because they’re built on top of the same Redis client. Install the respective packages and follow their guides:

If you prefer not to use the Aspire client integration, you can read the Aspire-injected connection properties from the environment and configure 📦 StackExchange.Redis directly:

C# — Program.cs
using StackExchange.Redis;
var connectionString = Environment.GetEnvironmentVariable("CACHE_URI");
var mux = await ConnectionMultiplexer.ConnectAsync(connectionString!);
var db = mux.GetDatabase();
// Use db to interact with Azure Cache for Redis...