ASP.NET Core 中的分散式快取

作者:Mohsin Nasir 與 smandia

Note

這不是這篇文章的最新版本。 關於目前版本,請參閱本文的 .NET 11 版本。

分散式快取是由多個應用程式伺服器共享的快取。 快取通常作為外部服務維護,供存取快取的應用程式伺服器使用。 分散式快取能提升 ASP.NET Core 應用程式的效能與可擴展性,尤其當雲端服務或伺服器叢集承載該應用程式時。

分散式快取相比其他快取案例有幾項優點:快取資料會儲存在個別的應用程式伺服器上。

當快取資料被分發時,資料會如下:

  • 在多個伺服器的請求之間保持一致性。
  • 即使在伺服器重新啟動和應用程式部署後,依然能夠保持存續。
  • 不使用本機記憶體。

依實作而定的分散式快取組態。 本文說明如何設定 SQL Server、Redis 或 Postgres 分散式快取。 也有非 Microsoft 的實作,如 NCache(GitHub 上的 NCache)、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程式庫會幫你序列化值,並在分散式快取之上新增處理程序內的主要快取和 stampede 保護。

建立分散式快取系統

在 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。

    • 針對本機開發:使用 Secret Manager 儲存 連接字串。

    • 對於 Azure:將 連接字串 儲存在像 Azure Key Vault 這樣的安全儲存庫中。

下列程式碼會啟用 Azure Cache for Redis:

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

前述程式碼假設主要連接字串(StackExchange.Redis)在設定中以鍵名 MyRedisConStr 儲存。

更多資訊請參見 Azure Managed Redis。

關於本地 Redis 快取替代方案的討論,請參見 GitHub /dotnet/aspnetcore issue #19542。

分散式記憶體快取

分散式記憶體快取(AddDistributedMemoryCache)是一個由框架提供的 IDistributedCache 實作,將項目儲存在記憶體中。 然而,分散式記憶體快取並不是真正的分散式快取。 應用程式實例會將快取的項目儲存在執行該應用程式的伺服器上。

分散式記憶體快取是開發與測試情境中有用的實作。 它對於單一伺服器在生產環境中也很有用,因為記憶體消耗不是問題。 實作分散式記憶體快取能將快取資料儲存進行抽象化。 如果需要多個節點或容錯,它可在未來實作真正的分散式快取解決方案。

範例應用程式在Development檔案環境中執行時,會利用分散式記憶體快取。

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 快取表的結構。

Note

應用程式應該使用IDistributedCache實例來操作快取值,而不是使用SqlServerCache實例。

範例應用程式在非開發SqlServerCache()環境中實作該Development類別,並以 Program.cs 檔案呈現:

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 快取

適用於 PostgreSQL 的 Azure 資料庫 可以透過 IDistributedCache 介面作為分散式快取後盾儲存。 適用於 PostgreSQL 的 Azure 資料庫 是一個完全託管、具備 AI 支援的資料庫即服務(DBaaS)產品,建立在開源的 PostgreSQL 引擎之上。 此設計以可預測的效能、強大的安全性、高可用性及無縫擴展性,支援關鍵任務工作負載。

安裝 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 套件,該套件支援 NCache 開源版 .NET Framework 及 .NET Core 應用程式。

  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 用戶端,或如以下章節所述建立新客戶端。

欲了解更多資訊,請參閱 使用 Azure Cosmos DB 的 Microsoft 快取擴充功能,以及 NuGet 套件的 GitHub 倉庫中的 README 檔案。

重複使用現有的用戶端

配置分散式快取最簡單的方法是重用現有的 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 物件中,供索引頁面使用。

每次 Index 頁面載入時,會透過該 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
  • 小組體驗

快取解決方案通常依賴記憶體內部儲存體來快速擷取快取的資料,但記憶體是有限的資源,而且成本高昂。 僅將常用的資料儲存在快取中。

對於大部分的應用程式,Redis 快取相比 SQL Server 快取,輸送量更高且延遲更低。 不過,還是建議使用效能評定來判斷快取策略的效能特性。

若 SQL Server 是分散式快取後備儲存,且快取與應用程式資料儲存/檢索共用同一資料庫,效能可能會下降。 建議做法是使用專用的 SQL Server 實例作為分散式快取後備儲存。