Set up Azure Cache for Redis in the AppHost
Esta página aún no está disponible en tu idioma.
This article is the reference for the Aspire Azure Cache for Redis Hosting integration. It enumerates the AppHost APIs — with examples for both AppHost.cs and apphost.ts — that you use to model an Azure managed Redis cache resource in your AppHost project.
If you’re new to the Azure Cache for Redis integration, start with the Get started with Azure Cache for Redis integrations guide. For how consuming apps read the connection information this page exposes, see Connect to Azure Cache for Redis.
Installation
Section titled “Installation”To start building an Aspire app that uses Azure Cache for Redis, install the 📦 Aspire.Hosting.Azure.Redis NuGet package:
aspire add azure-redisLearn more about aspire add in the command reference.
Or, choose a manual installation approach:
#:package Aspire.Hosting.Azure.Redis@*<PackageReference Include="Aspire.Hosting.Azure.Redis" Version="*" />aspire add azure-redisLearn more about aspire add in the command reference.
This updates your aspire.config.json with the Azure Cache for Redis hosting integration package:
{ "packages": { "Aspire.Hosting.Azure.Redis": "13.3.0" }}Add Azure Managed Redis resource
Section titled “Add Azure Managed Redis resource”Once you’ve installed the hosting integration in your AppHost project, you can add an Azure Managed Redis resource as shown in the following examples:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddAzureManagedRedis("cache");
builder.AddProject<Projects.ExampleProject>("apiservice") .WithReference(cache);
// After adding all resources, run the app...builder.Build().Run();import { createBuilder } from './.modules/aspire.js';
const builder = await createBuilder();
const cache = await builder.addAzureManagedRedis("cache");
await builder.addNodeApp("api", "./api", "index.js") .withReference(cache);
// After adding all resources, run the app...await builder.build().run();-
The resource is named
cacheand represents an Azure Managed Redis cache. Aspire generates the Bicep needed to provision it in Azure. -
By default, Aspire configures the resource to use Microsoft Entra ID (role-based access) authentication. No password is stored in the connection string. For more information, see Configure access key authentication.
-
The
WithReference(orwithReference) call configures a connection in the consuming project named after the resource, such ascachein the preceding example.
Run as a local Redis container
Section titled “Run as a local Redis container”The Azure Cache for Redis hosting integration supports running a local Redis container during development. This lets you develop and test your app locally without provisioning an Azure resource or connecting to an existing Azure Cache for Redis instance.
To run the resource as a container, chain a call to RunAsContainer (or runAsContainer):
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddAzureManagedRedis("cache") .RunAsContainer();
builder.AddProject<Projects.ExampleProject>("apiservice") .WithReference(cache);
// After adding all resources, run the app...builder.Build().Run();import { createBuilder } from './.modules/aspire.js';
const builder = await createBuilder();
const cache = await builder.addAzureManagedRedis("cache") .runAsContainer();
await builder.addNodeApp("api", "./api", "index.js") .withReference(cache);
// After adding all resources, run the app...await builder.build().run();The preceding code pulls the docker.io/library/redis container image and runs it locally. The consuming app connects to the container using a password-based connection string during development.
Connect to an existing Azure Cache for Redis instance
Section titled “Connect to an existing Azure Cache for Redis instance”If you already have an Azure Cache for Redis instance you want to use, call AsExisting (or asExisting) to annotate that the resource already exists rather than being provisioned:
var builder = DistributedApplication.CreateBuilder(args);
var existingRedisName = builder.AddParameter("existingRedisName");var existingRedisResourceGroup = builder.AddParameter("existingRedisResourceGroup");
var cache = builder.AddAzureManagedRedis("cache") .AsExisting(existingRedisName, existingRedisResourceGroup);
builder.AddProject<Projects.ExampleProject>("apiservice") .WithReference(cache);
// After adding all resources, run the app...builder.Build().Run();import { createBuilder } from './.modules/aspire.js';
const builder = await createBuilder();
const existingRedisName = await builder.addParameter("existingRedisName");const existingRedisResourceGroup = await builder.addParameter("existingRedisResourceGroup");
const cache = await builder.addAzureManagedRedis("cache") .asExisting(existingRedisName, { resourceGroup: existingRedisResourceGroup });
await builder.addNodeApp("api", "./api", "index.js") .withReference(cache);
// After adding all resources, run the app...await builder.build().run();For more information on treating Azure resources as existing resources, see Use existing Azure resources.
Configure access key authentication
Section titled “Configure access key authentication”By default, the Azure Managed Redis resource uses Microsoft Entra ID authentication. To switch to access key authentication (not recommended for production), call WithAccessKeyAuthentication (or withAccessKeyAuthentication):
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddAzureManagedRedis("cache") .WithAccessKeyAuthentication();
builder.AddProject<Projects.ExampleProject>("apiservice") .WithReference(cache);
// After adding all resources, run the app...builder.Build().Run();import { createBuilder } from './.modules/aspire.js';
const builder = await createBuilder();
const cache = await builder.addAzureManagedRedis("cache") .withAccessKeyAuthentication();
await builder.addNodeApp("api", "./api", "index.js") .withReference(cache);
// After adding all resources, run the app...await builder.build().run();When access key authentication is enabled, the generated Bicep stores the access key in an Azure Key Vault secret and injects it as the Password connection property. The connection string includes the password instead of relying on a managed identity token.
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 — the provisioning APIs generate it for you. When you publish your app, the generated Bicep is output alongside the manifest file. When you add an Azure Managed Redis resource, the following Bicep is generated:
@description('The location for the resource(s) to be deployed.')param location string = resourceGroup().location
resource cache 'Microsoft.Cache/redis@2024-11-01' = { name: take('cache-${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': 'cache' }}
output connectionString string = '${cache.properties.hostName},ssl=true'
output name string = cache.nameIn addition, 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 cache_outputs_name string
param principalId string
param principalName string
resource cache 'Microsoft.Cache/redis@2024-11-01' existing = { name: cache_outputs_name}
resource cache_contributor 'Microsoft.Cache/redis/accessPolicyAssignments@2024-11-01' = { name: guid(cache.id, principalId, 'Data Contributor') properties: { accessPolicyName: 'Data Contributor' objectId: principalId objectIdAlias: principalName } parent: cache}The generated Bicep provisions the Azure Cache for Redis instance and creates an access policy assignment so the consuming application can connect using its managed identity. The generated Bicep is a starting point that reflects the provisioning infrastructure configured in your AppHost. Customizations made directly to the Bicep files are overwritten on the next publish — make changes through the C# or TypeScript provisioning APIs instead.
Customize provisioning infrastructure
Section titled “Customize provisioning infrastructure”All Aspire Azure resources are subclasses of the AzureProvisioningResource type. This type enables Bicep customization through the ConfigureInfrastructure API:
var builder = DistributedApplication.CreateBuilder(args);
builder.AddAzureManagedRedis("cache") .ConfigureInfrastructure(infra => { var redisCache = infra.GetProvisionableResources() .OfType<RedisCache>() .Single();
redisCache.Sku = new RedisSku { Name = RedisSkuName.Standard, Family = RedisSkuFamily.C, Capacity = 1, }; redisCache.Tags.Add("ExampleKey", "Example value"); });
// After adding all resources, run the app...builder.Build().Run();import { createBuilder } from './.modules/aspire.js';
const builder = await createBuilder();
await builder.addAzureManagedRedis("cache") .configureInfrastructure(async (infra) => { // Use the AzureResourceInfrastructure API to customize Bicep // parameters or resources directly. await infra.addParameter("skuName", "Standard"); });
// After adding all resources, run the app...await builder.build().run();The preceding C# code retrieves the RedisCache resource from the infrastructure and updates the SKU to Standard tier with capacity 1, then adds a tag. The TypeScript AppHost exposes the same configureInfrastructure API for adding Bicep parameters and customizing resource configuration.
For more configuration options, see Azure.Provisioning customization.
Connection properties
Section titled “Connection properties”For the full reference of Azure Cache for Redis connection properties — and how consuming apps in C#, TypeScript, Python, and Go read them — see Connect to Azure Cache for Redis.
Hosting integration health checks
Section titled “Hosting integration health checks”The Azure Cache for Redis hosting integration automatically adds a health check for the resource when running as a local container. The health check verifies that the Redis instance is running and that a connection can be established.
The hosting integration relies on the 📦 AspNetCore.HealthChecks.Redis NuGet package to perform the health check.