Skip to content

缓存集成 ​

更新: 2026-10-16 15:20:09   字数: 0 字   时长: 0 分钟

Aspire 为 Redis 及兼容实现提供托管集成,本地开发时以容器方式启动,部署时映射为目标平台的托管服务。

支持的缓存 ​

缓存托管集成包添加方法
RedisAspire.Hosting.RedisAddRedis(name)
GarnetAspire.Hosting.GarnetAddGarnet(name)
ValkeyAspire.Hosting.ValkeyAddValkey(name)

Garnet / Valkey 是什么?

Garnet 是微软开源的 Redis 兼容存储,性能出色;Valkey 是 Redis 许可变更后由社区维护的分支。三者的集成使用方式几乎一致,互换成本很低。

基本用法 ​

csharp
var builder = DistributedApplication.CreateBuilder(args);

var cache = builder.AddRedis("cache")
    .WithDataVolume()          // 需要保留缓存内容时才加
    .WithRedisCommander();     // 附带 Redis Commander 管理界面(开发用)

builder.AddProject<Projects.Api>("api")
    .WithReference(cache)
    .WithHttpHealthCheck("/health");

builder.Build().Run();

在服务中消费 ​

csharp
builder.AddServiceDefaults();

// 注册 Redis 客户端(连接信息自动来自被引用的 cache 资源)
builder.AddRedisClient("cache");

// 或者注册分布式缓存实现
builder.AddRedisDistributedCache("cache");

// 或者注册输出缓存实现
builder.AddRedisOutputCache("cache");

使用:

csharp
app.MapGet("/products/{id}", async (string id, IDistributedCache cache) =>
{
    var cached = await cache.GetStringAsync(id);
    if (cached is not null)
    {
        return Results.Ok(cached);
    }

    var value = await LoadFromDatabaseAsync(id);
    await cache.SetStringAsync(id, value, new DistributedCacheEntryOptions
    {
        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
    });

    return Results.Ok(value);
});

在 AppHost 中设置缓存值 ​

开发阶段经常需要预置一些数据,WithCommand / WithEntrypoint 之外,最直接的做法是在资源就绪后写入:

csharp
var cache = builder.AddRedis("cache");

cache.OnResourceReady(async (resource, evt, ct) =>
{
    var connectionString = await resource.GetConnectionStringAsync(ct);
    // 使用 StackExchange.Redis 写入初始数据
    await SeedCacheAsync(connectionString!, ct);
});

发布与部署 ​

目标平台映射结果
Docker Composecache 容器 + 持久卷。
Kubernetes容器 + PersistentVolume。
Azure Container AppsAzure Cache for Redis(或兼容的托管服务)。
csharp
var cache = builder.AddAzureRedis("cache")
    .RunAsContainer();           // 本地以容器运行,发布时使用 Azure Cache for Redis

无密码还是有密码? ​

本地开发默认不启用密码,方便调试。生产环境请务必启用认证:

csharp
builder.AddRedis("cache")
    .WithPassword(builder.AddParameter("cache-password", secret: true));

不要把生产缓存开成无认证

发布到云环境时,Aspire 生成的部署产物会使用目标平台的认证机制。如果自行改写产物,请确保不只暴露了连接信息还开启了访问控制。

下一步 ​

你觉得这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度