# Connect to Azure Cache for Redis

<Image
  src={cacheRedisIcon}
  alt="Azure Cache for Redis logo"
  width={100}
  height={100}
  class:list={'float-inline-left icon'}
  data-zoom-off
/>

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](../azure-cache-redis-host/).

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.

## Connection properties

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 Name | Description |
| ------------- | ----------- |
| `Host`        | The hostname of the Azure Cache for Redis endpoint |
| `Port`        | The 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` |
| `Password`    | The access key. Empty when using Entra ID authentication; populated when using `WithAccessKeyAuthentication` or running as a local container |
| `Uri`         | The 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
```

## Connect from your app

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`](https://stackexchange.github.io/StackExchange.Redis/Basics.html) 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#](#read-environment-variables-in-c) section at the end of this tab.

#### Install the client integration

Install the [📦 Aspire.StackExchange.Redis](https://www.nuget.org/packages/Aspire.StackExchange.Redis) NuGet package in the client-consuming project:

<InstallDotNetPackage packageName="Aspire.StackExchange.Redis" />

#### Add the Redis client

In _Program.cs_, call `AddRedisClient` on your `IHostApplicationBuilder` to register an `IConnectionMultiplexer`:

```csharp title="C# — Program.cs"
builder.AddRedisClient(connectionName: "cache");
```
**Tip:** The `connectionName` must match the Azure Managed Redis resource name from the AppHost. For more information, see [Add Azure Managed Redis resource](../azure-cache-redis-host/#add-azure-managed-redis-resource).

Resolve the connection multiplexer through dependency injection:

```csharp title="C# — ExampleService.cs"
public class ExampleService(IConnectionMultiplexer connectionMux)
{
    // Use connection multiplexer...
}
```

#### Add keyed Redis clients

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

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

Then resolve each instance by key:

```csharp title="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](https://learn.microsoft.com/dotnet/core/extensions/dependency-injection#keyed-services).

#### Azure Entra ID authentication

To enable Microsoft Entra ID (managed identity) authentication for Azure Cache for Redis in C#, install the [📦 Aspire.Microsoft.Azure.StackExchangeRedis](https://www.nuget.org/packages/Aspire.Microsoft.Azure.StackExchangeRedis) NuGet package and use the `AddRedisClientBuilder` API with `WithAzureAuthentication`:

```csharp title="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.

#### Configuration

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`:

```csharp title="C# — Program.cs"
builder.AddRedisClient("cache");
```

The connection string is resolved from the `ConnectionStrings` section:

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

For more information, see [Stack Exchange Redis configuration](https://stackexchange.github.io/StackExchange.Redis/Configuration.html#basic-configuration-strings).

**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 title="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:

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

#### Client integration health checks

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.

#### Observability and telemetry

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.

#### Distributed caching and output caching

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:

- [Aspire.StackExchange.Redis.DistributedCaching](https://www.nuget.org/packages/Aspire.StackExchange.Redis.DistributedCaching) — see [Get started with Redis distributed caching](/integrations/caching/redis-distributed/redis-distributed-get-started/).
- [Aspire.StackExchange.Redis.OutputCaching](https://www.nuget.org/packages/Aspire.StackExchange.Redis.OutputCaching) — see [Get started with Redis output caching](/integrations/caching/redis-output/redis-output-get-started/).

#### Read environment variables in C\#

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](https://www.nuget.org/packages/StackExchange.Redis/) directly:

```csharp title="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...
```

Use [`go-redis`](https://github.com/redis/go-redis), the most actively maintained Go client for the RESP protocol:

```bash title="Terminal"
go get github.com/redis/go-redis/v9
```

Read the injected environment variables and connect. Azure Cache for Redis requires TLS, so configure the client accordingly:

```go title="Go — main.go"
package main

import (
    "context"
    "crypto/tls"
    "os"
    "strconv"
    "github.com/redis/go-redis/v9"
)

func main() {
    // Read Aspire-injected connection properties
    host := os.Getenv("CACHE_HOST")
    port := os.Getenv("CACHE_PORT")
    password := os.Getenv("CACHE_PASSWORD")

    portNum, _ := strconv.Atoi(port)

    rdb := redis.NewClient(&redis.Options{
        Addr:      host + ":" + port,
        Password:  password,
        DB:        0,
        TLSConfig: &tls.Config{ServerName: host},
    })
    defer rdb.Close()

    _ = rdb.Ping(context.Background()).Err()

    // Use rdb to interact with Azure Cache for Redis...
    _ = portNum
}
```

When running as a local container via `RunAsContainer`, you can use the simpler URI-based connection instead:

```go title="Go — main.go (local container)"
package main

import (
    "context"
    "os"
    "github.com/redis/go-redis/v9"
)

func main() {
    // Read the Aspire-injected connection URI
    opt, err := redis.ParseURL(os.Getenv("CACHE_URI"))
    if err != nil {
        panic(err)
    }

    rdb := redis.NewClient(opt)
    defer rdb.Close()

    _ = rdb.Ping(context.Background()).Err()
}
```
**Note:** When using Entra ID authentication (the default in Azure mode), no password is injected. To authenticate with managed identity from Go, use the [Azure SDK for Go](https://github.com/Azure/azure-sdk-for-go) to obtain a token and pass it as the password to the Redis client.

Install [`redis-py`](https://github.com/redis/redis-py), the official Python client for RESP servers:

```bash title="Terminal"
pip install redis
```

Read the injected environment variables and connect. Azure Cache for Redis requires TLS:

```python title="Python — app.py"
import os
import redis

# Read Aspire-injected connection properties
host = os.getenv("CACHE_HOST")
port = int(os.getenv("CACHE_PORT", "6380"))
password = os.getenv("CACHE_PASSWORD")  # empty when using Entra ID

# Connect with TLS enabled for Azure
client = redis.Redis(
    host=host,
    port=port,
    password=password or None,
    ssl=True,
    ssl_cert_reqs=None,
)

client.ping()
# Use client to interact with Azure Cache for Redis...
```

When running as a local container via `RunAsContainer`, you can use the simpler URI-based connection:

```python title="Python — app.py (local container)"
import os
import redis

# Read the Aspire-injected connection URI
client = redis.from_url(os.getenv("CACHE_URI"))

client.ping()
# Use client to interact with Redis...
```
**Note:** When using Entra ID authentication (the default in Azure mode), `CACHE_PASSWORD` is empty. To authenticate with managed identity from Python, use the [azure-identity](https://pypi.org/project/azure-identity/) package to obtain a token and pass it as the password to the Redis client.

Install [`ioredis`](https://github.com/redis/ioredis), the most popular RESP client for Node.js:

```bash title="Terminal"
npm install ioredis
```

Read the injected environment variables and connect. Azure Cache for Redis requires TLS:

```typescript title="TypeScript — index.ts"
import Redis from 'ioredis';

// Read Aspire-injected connection properties
const client = new Redis({
    host: process.env.CACHE_HOST,
    port: Number(process.env.CACHE_PORT ?? 6380),
    password: process.env.CACHE_PASSWORD || undefined,
    tls: { servername: process.env.CACHE_HOST },
});

await client.ping();
// Use client to interact with Azure Cache for Redis...
```

When running as a local container via `RunAsContainer`, you can use the simpler URI-based connection:

```typescript title="TypeScript — Connect with URI (local container)"
import Redis from 'ioredis';

const client = new Redis(process.env.CACHE_URI!);
```
**Note:** When using Entra ID authentication (the default in Azure mode), `CACHE_PASSWORD` is empty. To authenticate with managed identity from TypeScript, use the [`@azure/identity`](https://www.npmjs.com/package/@azure/identity) package to obtain a token and pass it as the password to the Redis client.
**Tip:** If your app expects specific environment variable names different from the Aspire defaults, you can pass individual connection properties from the AppHost. See [Use existing Azure resources](/integrations/cloud/azure/overview/#use-existing-azure-resources) for guidance on customizing environment variable injection.