Azure Cache for Redis integration
Esta página aún no está disponible en tu idioma.
Azure Cache for Redis provides an in-memory data store based on the Redis software. Redis improves the performance and scalability of an application that uses backend data stores heavily. It’s able to process large volumes of application requests by keeping frequently accessed data in the server memory, which can be written to and read from quickly. Redis brings a critical low-latency and high-throughput data storage solution to modern applications.
Azure Cache for Redis offers both the Redis open-source (OSS Redis) and a commercial product from Redis Inc. (Redis Enterprise) as a managed service. It provides secure and dedicated Redis server instances and full Redis API compatibility. Microsoft operates the service, hosted on Azure, and usable by any application within or outside of Azure.
Hosting integration
Section titled “Hosting integration”The Aspire Azure Cache for Redis hosting integration models the Redis cache as the AzureRedisResource type. To access this type and APIs for expressing them within your AppHost project, install the 📦 Aspire.Hosting.Azure.Redis NuGet package:
aspire add azure-redisLa CLI de Aspire es interactiva; asegúrate de seleccionar el resultado adecuado cuando se te pida:
Select an integration to add:
> azure-redis (Aspire.Hosting.Azure.Redis)> Other results listed as selectable options...#:package Aspire.Hosting.Azure.Redis@*<PackageReference Include="Aspire.Hosting.Azure.Redis" Version="*" />Add an Azure Cache for Redis resource
Section titled “Add an Azure Cache for Redis resource”To add an Azure Cache for Redis resource to your AppHost project, call the AddAzureRedis method providing a name:
var builder = DistributedApplication.CreateBuilder(args);
var redis = builder.AddAzureRedis("redis");
builder.AddProject<Projects.ExampleProject>() .WithReference(redis);
// After adding all resources, run the app...The preceding code adds an Azure Redis resource named redis to the AppHost project. The WithReference method passes the connection information to the ExampleProject project.
Connect to an existing Azure Cache for Redis instance
Section titled “Connect to an existing Azure Cache for Redis instance”You might have an existing Azure Cache for Redis service that you want to connect to. You can chain a call to annotate that your AzureRedisCacheResource is an existing resource:
var builder = DistributedApplication.CreateBuilder(args);
var existingRedisName = builder.AddParameter("existingRedisName");var existingRedisResourceGroup = builder.AddParameter("existingRedisResourceGroup");
var redis = builder.AddAzureRedis("redis") .AsExisting(existingRedisName, existingRedisResourceGroup);
builder.AddProject<Projects.ExampleProject>() .WithReference(redis);
// After adding all resources, run the app...For more information on treating Azure Redis resources as existing resources, see Use existing Azure resources.
Run Azure Cache for Redis resource as a container
Section titled “Run Azure Cache for Redis resource as a container”The Azure Cache for Redis hosting integration supports running the Redis server as a local container. This is beneficial for situations where you want to run the Redis server locally for development and testing purposes, avoiding the need to provision an Azure resource or connect to an existing Azure Cache for Redis server.
To make use of the docker.io/library/redis container image, and run the Azure Cache for Redis instance as a container locally, chain a call to RunAsContainer, as shown in the following example:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddAzureRedis("azcache") .RunAsContainer();
builder.AddProject<Projects.ExampleProject>() .WithReference(cache);
// After adding all resources, run the app...The preceding code configures the Redis resource to run locally in a container.
Configure the Azure Cache for Redis resource to use access key authentication
Section titled “Configure the Azure Cache for Redis resource to use access key authentication”By default, the Azure Cache for Redis resource is configured to use Microsoft Entra ID authentication. If you want to use password authentication (not recommended), you can configure the server to use password authentication by calling the WithAccessKeyAuthentication method:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddAzureRedis("azcache") .WithAccessKeyAuthentication();
builder.AddProject<Projects.ExampleProject>() .WithReference(cache);
// After adding all resources, run the app...The preceding code configures the Azure Cache for Redis resource to use access key authentication. This alters the generated Bicep to use access key authentication instead of Microsoft Entra ID authentication. In other words, the connection string will contain a password, and will be added to an Azure Key Vault secret.
Provisioning-generated Bicep
Section titled “Provisioning-generated Bicep”If you’re new to Bicep, it’s a domain-specific language for defining Azure resources. With Aspire, you don’t need to write Bicep by-hand, instead the provisioning APIs generate Bicep for you. When you publish your app, the generated Bicep is output alongside the manifest file. When you add an Azure Cache for Redis resource, the following Bicep is generated:
@description('The location for the resource(s) to be deployed.')param location string = resourceGroup().location
resource redis 'Microsoft.Cache/redis@2024-11-01' = { name: take('redis-${uniqueString(resourceGroup().id)}', 63) location: location properties: { sku: { name: 'Basic' family: 'C' capacity: 1 } enableNonSslPort: false disableAccessKeyAuthentication: true minimumTlsVersion: '1.2' redisConfiguration: { 'aad-enabled': 'true' } } tags: { 'aspire-resource-name': 'redis' }}
output connectionString string = '${redis.properties.hostName},ssl=true'
output name string = redis.nameThe preceding Bicep is a module that provisions an Azure Cache for Redis resource. Additionally, role assignments are created for the Azure resource in a separate module:
@description('The location for the resource(s) to be deployed.')param location string = resourceGroup().location
param redis_outputs_name string
param principalId string
param principalName string
resource redis 'Microsoft.Cache/redis@2024-11-01' existing = { name: redis_outputs_name}
resource redis_contributor 'Microsoft.Cache/redis/accessPolicyAssignments@2024-11-01' = { name: guid(redis.id, principalId, 'Data Contributor') properties: { accessPolicyName: 'Data Contributor' objectId: principalId objectIdAlias: principalName } parent: redis}In addition to the Azure Cache for Redis, it also provisions an access policy assignment to the application access to the cache. The generated Bicep is a starting point and is influenced by changes to the provisioning infrastructure in C#. Customizations to the Bicep file directly will be overwritten, so make changes through the C# provisioning APIs to ensure they are reflected in the generated files.
Customize provisioning infrastructure
Section titled “Customize provisioning infrastructure”All Aspire Azure resources are subclasses of the AzureProvisioningResource type. This type enables the customization of the generated Bicep by providing a fluent API to configure the Azure resources using the ConfigureInfrastructure API:
var builder = DistributedApplication.CreateBuilder(args);
builder.AddAzureRedis("redis") .WithAccessKeyAuthentication() .ConfigureInfrastructure(infra => { var redis = infra.GetProvisionableResources() .OfType<RedisResource>() .Single();
redis.Sku = new() { Family = RedisSkuFamily.BasicOrStandard, Name = RedisSkuName.Standard, Capacity = 1, }; redis.Tags.Add("ExampleKey", "Example value"); });The preceding code:
- Chains a call to the
ConfigureInfrastructureAPI:- The
infraparameter is an instance of theAzureResourceInfrastructuretype. - The provisionable resources are retrieved by calling the
GetProvisionableResourcesmethod. - The single
RedisResourceis retrieved. - The
Skuis set with a family ofBasicOrStandard, a name ofStandard, and a capacity of1. - A tag is added to the Redis resource with a key of
ExampleKeyand a value ofExample value.
- The
There are many more configuration options available to customize the Redis resource. For more information, see Azure.Provisioning customization.
Client integration
Section titled “Client integration”The Aspire Azure Cache for Redis client integration is used to connect to an Azure Redis cache using StackExchange.Redis. To get started with the Aspire Azure Cache for Redis client integration, install the 📦 Aspire.StackExchange.Redis NuGet package.
dotnet add package Aspire.StackExchange.Redis#:package Aspire.StackExchange.Redis@*<PackageReference Include="Aspire.StackExchange.Redis" Version="*" />Add Redis client
Section titled “Add Redis client”In the Program.cs file of your client-consuming project, call the AddRedisClient extension method to register an IConnectionMultiplexer for use via the dependency injection container. The method takes a connection name parameter:
builder.AddRedisClient(connectionName: "redis");After adding the IConnectionMultiplexer, you can retrieve the connection instance using dependency injection:
public class ExampleService(IConnectionMultiplexer redis){ // Use redis...}For more information, see:
- StackExchange.Redis documentation for examples on using the
IConnectionMultiplexer. - Dependency injection in .NET for details on dependency injection.
Add Redis distributed cache
Section titled “Add Redis distributed cache”For caching scenarios, you can add a Redis-based distributed cache using the AddRedisDistributedCache method:
builder.AddRedisDistributedCache(connectionName: "redis");This registers an IDistributedCache implementation backed by Redis:
public class ExampleService(IDistributedCache cache){ // Use cache...}Add Redis output cache
Section titled “Add Redis output cache”For output caching scenarios in ASP.NET Core, you can add a Redis-based output cache using the AddRedisOutputCache method:
builder.AddRedisOutputCache(connectionName: "redis");This configures Redis as the output cache store for your web application.
Add keyed Redis client
Section titled “Add keyed Redis client”There might be situations where you want to register multiple IConnectionMultiplexer instances with different connection names. To register keyed Redis clients, call the AddKeyedRedisClient method:
builder.AddKeyedRedisClient(name: "primary-cache");builder.AddKeyedRedisClient(name: "secondary-cache");Then you can retrieve the connection instances using dependency injection:
public class ExampleService( [KeyedService("primary-cache")] IConnectionMultiplexer primaryRedis, [KeyedService("secondary-cache")] IConnectionMultiplexer secondaryRedis){ // Use redis connections...}For more information, see Keyed services in .NET.
Configuration
Section titled “Configuration”The Aspire Azure Cache for Redis library provides multiple options to configure the Redis connection based on the requirements and conventions of your project. A ConnectionString is required.
Use a connection string
Section titled “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 AddRedisClient:
builder.AddRedisClient(connectionName: "redis");The connection information is retrieved from the ConnectionStrings configuration section:
{ "ConnectionStrings": { "redis": "myredis.redis.cache.windows.net:6380,password=your_password,ssl=True" }}Use configuration providers
Section titled “Use configuration providers”The library supports Microsoft.Extensions.Configuration. It loads settings from configuration using the Aspire:StackExchange:Redis key:
{ "Aspire": { "StackExchange": { "Redis": { "DisableHealthChecks": true, "DisableTracing": false } } }}Use inline delegates
Section titled “Use inline delegates”You can configure settings inline:
builder.AddRedisClient( "redis", settings => settings.DisableHealthChecks = true);Observability and telemetry
Section titled “Observability and telemetry”Aspire integrations automatically set up Logging, Tracing, and Metrics configurations.
Logging
Section titled “Logging”The Aspire Azure Cache for Redis integration uses standard .NET logging for connection events and errors.
Tracing
Section titled “Tracing”The Aspire Azure Cache for Redis integration will emit the following tracing activities using OpenTelemetry:
StackExchange.Redis.*
Metrics
Section titled “Metrics”The Aspire Azure Cache for Redis integration currently doesn’t expose custom metrics by default, but uses standard Redis monitoring capabilities.