ASP.NET Core 中的分布式缓存

作者:Mohsin Nasir 和 smandia

Note

此版本不是本文的最新版本。 有关当前版本,请参阅本文的 .NET 11 版本。

分布式缓存是由多个应用服务器共享的缓存。 缓存通常作为访问缓存的应用服务器的外部服务进行维护。 分布式缓存可以提高 ASP.NET Core应用的性能和可伸缩性,尤其是在云服务或服务器场托管应用时。

与其他将缓存数据存储在单个应用服务器上的缓存方案相比,分布式缓存具有多个优势。

当缓存数据被分发时,数据:

  • 在向多个服务器发出请求时保持一致。
  • 在进行服务器重启和应用部署后仍然有效。
  • 不使用本地内存。

分布式缓存配置是特定于实现的。 本文介绍如何配置 SQL Server、Redis 或 Postgres 分布式缓存。 还可以使用非Microsoft实现,例如 NCache(NCache on GitHub)、Azure Cosmos DB 和 Postgres。 无论选择哪个实现,应用都会使用 IDistributedCache 接口与缓存交互。

查看或下载示例代码 (如何下载)

Warning

本文使用不需要对用户进行身份验证的本地数据库。 生产应用应使用可用的最安全的身份验证流。 有关已部署测试和生产应用的身份验证的详细信息,请参阅安全身份验证流。

Prerequisites

为所使用的分布式缓存提供程序添加包引用:

使用 IDistributedCache 接口

IDistributedCache 接口提供以下方法来处理分布式缓存实现中的项:

  • Get,GetAsync:接受一个字符串键;如果在缓存中找到该项,则以 byte[] 数组形式检索缓存项。
  • Set,SetAsync:使用字符串键向缓存中添加项(作为 byte[] 数组)。
  • Refresh, RefreshAsync:根据其键刷新缓存中的项,重置其滑动过期超时时间(如果有)。
  • Remove, RemoveAsync:根据缓存项的字符串键删除缓存项。

存储字节数组以外的对象

IDistributedCache 将值存储为 byte[] 数组。 若要缓存其他类型,请先将其序列化。 以下扩展方法使用 System.Text.Json 将任何可序列化类型存储为 UTF-8 JSON:

using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;

public static class DistributedCacheExtensions
{
    public static Task SetAsync<T>(this IDistributedCache cache, string key, T value,
        DistributedCacheEntryOptions options, CancellationToken token = default) =>
        cache.SetAsync(key, JsonSerializer.SerializeToUtf8Bytes(value), options, token);

    public static async Task<T?> GetAsync<T>(this IDistributedCache cache, string key,
        CancellationToken token = default)
    {
        var bytes = await cache.GetAsync(key, token);
        return bytes is null ? default : JsonSerializer.Deserialize<T>(bytes);
    }
}

GetAsync<T> 返回类型的默认值,例如 null,当键不在缓存中时。

Tip

HybridCache 库将为你序列化值,并在分布式缓存之上添加进程内主缓存和踩踏防护。

建立分布式缓存服务

在 IDistributedCache 文件中注册 实现。 本文介绍了以下框架提供的实现:

分布式 Redis 缓存

分布式 Redis 缓存提供最佳性能,建议用于生产应用。 Redis 是一种 开放源代码 的内存中数据存储,通常用作分布式缓存。 可以为 Azure 托管的 ASP.NET Core 应用配置 Azure Cache for Redis,并使用 Azure Cache for Redis 进行本地开发。 有关详细信息,请参阅 “查看缓存建议”。

应用通过调用RedisCache方法,用AddStackExchangeRedisCache实例配置缓存实现。 对于 输出缓存,请使用 AddStackExchangeRedisOutputCache 该方法。

  1. 创建 Azure Cache for Redis 的实例。

  2. 将主连接字符串(StackExchange.Redis)复制到 Configuration。

以下代码启用 Azure Cache for Redis:

builder.Services.AddStackExchangeRedisCache(options =>
 {
     options.Configuration = builder.Configuration.GetConnectionString("MyRedisConStr");
     options.InstanceName = "SampleInstance";
 });

前面的代码假定主连接字符串(StackExchange.Redis)保存在配置中,密钥名称为 MyRedisConStr。

有关详细信息,请参阅 Azure 托管 Redis。

有关本地 Redis 缓存的替代方法的讨论,请参阅 GitHub /dotnet/aspnetcore 问题 #19542。

分布式内存缓存

分布式内存缓存 (AddDistributedMemoryCache) 是一种框架提供的实现 IDistributedCache ,用于将项存储在内存中。 但是,分布式内存缓存不是实际的分布式缓存。 应用实例将缓存的项存储在运行应用的服务器上。

分布式内存缓存是开发和测试方案的有用实现。 在生产环境中,对于内存消耗不是问题的单个服务器来说,它也很有用。 实现分布式内存缓存以抽象化缓存数据的存储。 如果需要多个节点或容错,它允许在未来实现真正的分布式缓存解决方案。

当应用在 DevelopmentProgram.cs 文件中的环境中运行时,示例应用会使用分布式内存缓存。

builder.Services.AddDistributedMemoryCache();

分布式SQL Server缓存

分布式SQL Server缓存实现(AddDistributedSqlServerCache)允许分布式缓存使用SQL Server数据库作为其后盾存储。 要在 SQL Server 实例中创建 SQL Server 缓存项表,可以使用 sql-cache 工具。 该工具使用指定的名称和架构来创建表。

通过运行 sql-cache create 命令在 SQL Server 中创建一个表。 提供 SQL Server 实例 (Data Source)、数据库 (Initial Catalog)、架构(例如 dbo)和表名(例如 TestCache):

dotnet sql-cache create "Data Source=(localdb)/MSSQLLocalDB;Initial Catalog=DistCache;Integrated Security=True;" dbo TestCache

工具成功后,将记录消息:

Table and index were created successfully.

通过 sql-cache 工具创建的表具有以下架构:

显示使用“sql-cache create”命令创建的SQL Server缓存表的架构的屏幕截图。

或者,可以使用 T-SQL 直接创建表和索引,例如,通过SQL Server Management Studio或数据库迁移脚本:

CREATE TABLE [dbo].[TestCache](
    [Id] nvarchar(449) COLLATE SQL_Latin1_General_CP1_CS_AS NOT NULL,
    [Value] varbinary(max) NOT NULL,
    [ExpiresAtTime] datetimeoffset NOT NULL,
    [SlidingExpirationInSeconds] bigint NULL,
    [AbsoluteExpiration] datetimeoffset NULL,
    PRIMARY KEY (Id)
);

CREATE NONCLUSTERED INDEX Index_ExpiresAtTime ON [dbo].[TestCache](ExpiresAtTime);

Note

Id配置的最大长度为 449 个字符,以确保主键保留在SQL Server的 900 字节索引限制内,并使用SQL_Latin1_General_CP1_CS_AS排序规则来维护区分大小写的缓存密钥。 Index_ExpiresAtTime非聚集索引可有效删除过期的缓存项。

Note

应用应通过使用实例 IDistributedCache而不是实例 SqlServerCache来操作缓存值。

示例应用在SqlServerCache文件中的非开发(Development)环境中实现类:

builder.Services.AddDistributedSqlServerCache(options =>
{
    options.ConnectionString = builder.Configuration.GetConnectionString(
        "DistCache_ConnectionString");
    options.SchemaName = "dbo";
    options.TableName = "TestCache";
});

Note

属性(如ConnectionString,SchemaName和TableName)通常存储在源代码管理之外。 例如, 机密管理器 或 appsettings.json 或 appsettings.{Environment}.json 文件可能会存储属性。 连接字符串中可能包含不应存入源代码管理系统的凭据。

有关详细信息,请参阅 Azure 上的 SQL 数据库。

分布式 Postgres 缓存

Azure Database for PostgreSQL可以通过 IDistributedCache 接口用作分布式缓存的后备存储。 Azure Database for PostgreSQL是基于开源 PostgreSQL 引擎构建的完全托管的、AI 就绪的数据库即服务(DBaaS)产品。 此设计支持任务关键型工作负荷,具有可预测的性能、可靠的安全性、高可用性和无缝可伸缩性。

安装 Microsoft.Extensions.Caching.Postgres NuGet 包后,按如下所示配置分布式缓存:

  1. 注册服务。

    using Microsoft.Extensions.DependencyInjection;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Register the Postgres distributed cache.
    builder.Services.AddDistributedPostgresCache(options => {
       options.ConnectionString = builder.Configuration.GetConnectionString("PostgresCache");
       options.SchemaName = builder.Configuration.GetValue<string>("PostgresCache:SchemaName", "public");
       options.TableName = builder.Configuration.GetValue<string>("PostgresCache:TableName", "cache");
       options.CreateIfNotExists = builder.Configuration.GetValue<bool>("PostgresCache:CreateIfNotExists", true);
       options.UseWAL = builder.Configuration.GetValue<bool>("PostgresCache:UseWAL", false);
    
       // Optional: Configure expiration settings.
    
       var expirationInterval = builder.Configuration.GetValue<string>("PostgresCache:ExpiredItemsDeletionInterval");
       if (!string.IsNullOrEmpty(expirationInterval) && TimeSpan.TryParse(expirationInterval, out var interval)) {
           options.ExpiredItemsDeletionInterval = interval;
       }
    
       var slidingExpiration = builder.Configuration.GetValue<string>("PostgresCache:DefaultSlidingExpiration");
       if (!string.IsNullOrEmpty(slidingExpiration) && TimeSpan.TryParse(slidingExpiration, out var sliding)) {
           options.DefaultSlidingExpiration = sliding;
       }
    });
    
    var app = builder.Build();
    
  2. 使用缓存。

    public class MyService {
        private readonly IDistributedCache _cache;
    
        public MyService(IDistributedCache cache) {
            _cache = cache;
        }
    
        public async Task<string> GetDataAsync(string key) {
            var cachedData = await _cache.GetStringAsync(key);
    
            if (cachedData == null) {
    
                // Fetch the data from source.
                var data = await FetchDataFromSource();
    
                // Cache the data with options.
                var options = new DistributedCacheEntryOptions {
                   AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30),
                   SlidingExpiration = TimeSpan.FromMinutes(5)
                };
    
                await _cache.SetStringAsync(key, data, options);
                return data;
            }
    
            return cachedData;
        }
    }
    

分布式 NCache 缓存

NCache 是使用 .NET 原生开发的 开放源代码 内存分布式缓存。 NCache 既可以在本地工作,也可配置为在 Azure 或其他托管平台上运行的 ASP.NET Core 应用的分布式缓存群集。

若要在本地计算机上安装和配置 NCache,请参阅 入门指南。

若要配置 NCache,请执行以下操作:

  1. 安装 NCache SDK NuGet 包,该包支持用于 .NET Framework 和 .NET Core 应用的 NCache Opensource。

  2. 在 客户端配置 ( client.ncconf 文件)中配置缓存群集。

  3. 将以下代码添加到 Program.cs 文件:

builder.Services.AddNCacheDistributedCache(configuration =>
{
    configuration.CacheName = "democache";
    configuration.EnableLogs = true;
    configuration.ExceptionsEnabled = true;
});

分布式Azure Cosmos DB缓存

Azure Cosmos DB 可以在 ASP.NET Core 中使用 IDistributedCache 接口配置为会话状态提供程序。 Azure Cosmos DB 是一个完全托管的 NoSQL 和关系数据库,适用于新式应用程序开发,为任务关键型应用程序提供高可用性、可伸缩性和低延迟的数据访问。

安装Microsoft.Extensions.Caching.Cosmos NuGet 包后,配置 Azure Cosmos DB 分布式缓存。 可以使用现有的Azure Cosmos DB客户端或创建新的客户端,如以下部分所述。

有关详细信息,请参阅 Microsoft 缓存扩展使用 Azure Cosmos DB,以及 NuGet 包的 GitHub 存储库自述文件。

重用现有客户端

配置分布式缓存的最简单方法是重用现有Azure Cosmos DB客户端。 在这种情况下,在处置提供程序时不会处置 CosmosClient 实例。

services.AddCosmosCache((CosmosCacheOptions cacheOptions) =>
{
    cacheOptions.ContainerName = Configuration["CosmosCacheContainer"];
    cacheOptions.DatabaseName = Configuration["CosmosCacheDatabase"];
    cacheOptions.CosmosClient = existingCosmosClient;
    cacheOptions.CreateIfNotExists = true;
});

创建新客户端

或者,实例化新客户端。 在这种情况下,在处置提供程序时会处置 CosmosClient 实例。

services.AddCosmosCache((CosmosCacheOptions cacheOptions) =>
{
    cacheOptions.ContainerName = Configuration["CosmosCacheContainer"];
    cacheOptions.DatabaseName = Configuration["CosmosCacheDatabase"];
    cacheOptions.ClientBuilder = new CosmosClientBuilder(Configuration["CosmosConnectionString"]);
    cacheOptions.CreateIfNotExists = true;
});

使用分布式缓存

要使用 IDistributedCache 接口,请在应用中请求 IDistributedCache 实例。 该实例由依赖项注入 (DI) 提供。

示例应用启动时,实例 IDistributedCache 将注入 到Program.cs 文件中。 使用 IHostApplicationLifetime 接口缓存当前时间。 (有关详细信息,请参阅.NET泛型主机:IHostApplicationLifetime.)

app.Lifetime.ApplicationStarted.Register(() =>
{
    var currentTimeUTC = DateTime.UtcNow.ToString();
    byte[] encodedCurrentTimeUTC = System.Text.Encoding.UTF8.GetBytes(currentTimeUTC);
    var options = new DistributedCacheEntryOptions()
        .SetSlidingExpiration(TimeSpan.FromSeconds(20));
    app.Services.GetRequiredService<IDistributedCache>()
                              .Set("cachedTimeUTC", encodedCurrentTimeUTC, options);
});

示例应用将 IDistributedCache 实例注入到 IndexModel 对象中,以便由索引页使用。

每次加载索引页时,都会使用 OnGetAsync 该方法检查缓存的时间。 如果缓存的时间未过期,则会显示时间。 如果自上次访问缓存时间(加载此页的最后一次时间)以来已用 20 秒,则页面将显示消息“ 缓存时间已过期”。

通过选择 “重置缓存时间 ”选项,立即将缓存时间更新到当前时间。 此操作触发 OnPostResetCachedTime 处理程序方法。

public class IndexModel : PageModel
{
    private readonly IDistributedCache _cache;

    public IndexModel(IDistributedCache cache)
    {
        _cache = cache;
    }

    public string? CachedTimeUTC { get; set; }
    public string? ASP_Environment { get; set; }

    public async Task OnGetAsync()
    {
        CachedTimeUTC = "Cached Time Expired";
        var encodedCachedTimeUTC = await _cache.GetAsync("cachedTimeUTC");

        if (encodedCachedTimeUTC != null)
        {
            CachedTimeUTC = Encoding.UTF8.GetString(encodedCachedTimeUTC);
        }

        ASP_Environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
        if (String.IsNullOrEmpty(ASP_Environment))
        {
            ASP_Environment = "Null, so Production";
        }
    }

    public async Task<IActionResult> OnPostResetCachedTime()
    {
        var currentTimeUTC = DateTime.UtcNow.ToString();
        byte[] encodedCurrentTimeUTC = Encoding.UTF8.GetBytes(currentTimeUTC);
        var options = new DistributedCacheEntryOptions()
            .SetSlidingExpiration(TimeSpan.FromSeconds(20));
        await _cache.SetAsync("cachedTimeUTC", encodedCurrentTimeUTC, options);

        return RedirectToPage();
    }
}

Note

对于具有内置实现的 IDistributedCache 实例,无需使用单例或范围限定生存期。

你也可以在可能需要的任何地方创建一个 IDistributedCache 实例,而不是使用依赖注入(DI)。 但是,在代码中创建实例会使代码难以测试和违反 显式依赖项原则。

查看缓存建议

确定接口的 IDistributedCache 哪个实现最适合你的应用时,请考虑以下几点:

  • 现有基础结构
  • 性能要求
  • Cost
  • 团队体验

缓存解决方案通常依靠内存中存储来提供对缓存数据的快速检索,但内存是一种有限的资源并且扩展成本很高。 仅将常用数据存储在缓存中。

对于大多数应用来说,与 SQL Server 缓存相比,Redis 缓存可提供更高的吞吐量和更低的延迟。 但建议进行基准测试来确定缓存策略的性能特征。

如果 SQL Server 是分布式缓存的后端存储,并且缓存与应用数据的存储/检索使用相同的数据库,性能可能会降低。 建议的方法是使用专用的 SQL Server 实例作为分布式缓存的后备存储。