1. 程式人生 > >Asp.Net Core 輕鬆學-正確使用分散式快取

Asp.Net Core 輕鬆學-正確使用分散式快取

前言

    本來昨天應該更新的,但是由於各種原因,抱歉,讓追這個系列的朋友久等了。上一篇文章 在.Net Core 使用快取和配置依賴策略 講的是如何使用本地快取,那麼本篇文章就來了解一下如何使用分散式快取,通過本章,你將瞭解到如何使用分散式快取,以及最重要的是,如何選擇適合自己的分散式快取;本章主要包含兩個部分:

內容提要

  1. 使用 SqlServer 分散式快取
  2. 使用 Redis 分散式快取
  3. 實現自定義的分散式快取客戶端註冊擴充套件
  4. 關於本示例的使用說明

1. 使用 SqlServer 分散式快取

1.1 準備工作,請依照以下步驟實施
  • 1 建立一個 Asp.Net Core MVC 測試專案:Ron.DistributedCacheDemo
  • 2 為了使用 SqlServer 作為分散式快取的資料庫,需要在專案中引用 Microsoft.EntityFrameworkCore 相關元件
  • 3 在 SqlServer 資料庫引擎中建立一個數據庫,命名為:TestDb
  • 4 開啟 Ron.DistributedCacheDemo 專案根目錄,執行建立快取資料表的操作,執行命令後如果輸出資訊:Table and index were created successfully. 表示快取表建立成功
dotnet sql-cache create "Server=.\SQLEXPRESS;User=sa;Password=123456;Database=TestDb" dbo AspNetCoreCache

1.2 開始使用 SqlServer 分散式快取

.Net Core 中的分散式快取統一介面是 IDistributedCache 該介面定義了一些對快取常用的操作,比如我們常見的 Set/Get 方法,而 SqlServer 分散式快取由 SqlServerCache 類實現,該類位於名稱空間 Microsoft.Extensions.Caching.SqlServer 中

  • 在 Startup.cs 中註冊分散式快取
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedSqlServerCache(options =>
            {
                options.SystemClock = new BLL.LocalSystemClock();
                options.ConnectionString = this.Configuration["ConnectionString"];
                options.SchemaName = "dbo";
                options.TableName = "AspNetCoreCache";
                options.DefaultSlidingExpiration = TimeSpan.FromMinutes(1);
                options.ExpiredItemsDeletionInterval = TimeSpan.FromMinutes(5);
            });
            ...
        }

上面的方法 ConfigureServices(IServiceCollection services) 中使用 services.AddDistributedSqlServerCache() 這個擴充套件方法引入了 SqlServer 分散式快取,並作了一些簡單的配置,該配置是由 SqlServerCacheOptions 決定的,SqlServerCacheOptions 的配置非常重要,這裡強烈建議大家手動配置

1.3 瞭解 SqlServerCacheOptions,先來看一下SqlServerCacheOptions 的結構
namespace Microsoft.Extensions.Caching.SqlServer
{
    public class SqlServerCacheOptions : IOptions<SqlServerCacheOptions>
    {
        public SqlServerCacheOptions();
        // 快取過期掃描時鐘
        public ISystemClock SystemClock { get; set; }
        // 快取過期逐出時間,預設為 30 分鐘
        public TimeSpan? ExpiredItemsDeletionInterval { get; set; }
        // 快取資料庫連線字串
        public string ConnectionString { get; set; }
        // 快取表所屬架構
        public string SchemaName { get; set; }
        // 快取表名稱
        public string TableName { get; set; }
        // 快取預設過期時間,預設為 20 分鐘
        public TimeSpan DefaultSlidingExpiration { get; set; }
    }
}

該配置非常簡單,僅是對快取使用的基本配置
首先,使用 options.SystemClock 配置了一個本地時鐘,接著設定快取過期時間為 1 分鐘,快取過期後逐出時間為 5 分鐘,其它則是連線資料庫的各項配置
在快取過期掃描的時候,使用的時間正是 options.SystemClock 該時鐘的時間,預設情況下,該時鐘使用 UTC 時間,在我的電腦上,UTC 時間是得到的是美國時間,所以這裡實現了一個本地時鐘,程式碼非常簡單,只是獲取一個本地時間

    public class LocalSystemClock : Microsoft.Extensions.Internal.ISystemClock
    {
        public DateTimeOffset UtcNow => DateTime.Now;
    }
1.4 在控制器中使用分散式快取
  • 首先使用依賴注入,在 HomeController 中獲得 IDistributedCache 的例項物件,該例項物件的實現型別為 SqlServerCache,然後通過 Index 方法增加一項快取 CurrentTime 並設定其值為當前時間,然後再另一介面 GetValue 中取出該 CurrentTime 的值
    [Route("api/Home")]
    [ApiController]
    public class HomeController : Controller
    {
        private IDistributedCache cache;
        public HomeController(IDistributedCache cache)
        {
            this.cache = cache;
        }

        [HttpGet("Index")]
        public async Task<ActionResult<string>> SetTime()
        {
            var CurrentTime = DateTime.Now.ToString();
            await this.cache.SetStringAsync("CurrentTime", CurrentTime);
            return CurrentTime;
        }

        [HttpGet("GetTime")]
        public async Task<ActionResult<string>> GetTime()
        {
            var CurrentTime = await this.cache.GetStringAsync("CurrentTime");
            return CurrentTime;
        }
    }
  • 執行程式,開啟地址:http://localhost:5000/api/home/settime,然後檢視快取資料庫,快取項 CurrentTime 已存入資料庫中

  • 訪問介面:http://localhost:5000/api/home/gettime 得到快取項 CurrentTime 的值

  • 等到超時時間過期後,再到資料庫檢視,發現快取項 CurrentTime 還在資料庫中,這是因為快取清理機制造成的
1.5 快取清理

在快取過期後,每次呼叫 Get/GetAsync 方法都會 呼叫 SqlServerCache 的 私有方法 ScanForExpiredItemsIfRequired() 進行一次掃描,然後清除所有過期的快取條目,掃描方法執行過程也很簡單,就是直接執行資料庫查詢語句

DELETE FROM {0} WHERE @UtcNow > ExpiresAtTime

值得注意的是,在非同步方法中使用同步呼叫不會觸發快取逐出,因為其執行緒退出導致 Task.Run 未能執行,比如下面的程式碼

        [HttpGet("GetTime")]
        public async Task<ActionResult<string>> GetTime()
        {
            var CurrentTime = this.cache.GetString("CurrentTime");
            return CurrentTime;
        }

將導致 SqlServerCache 無法完整執行方法 ScanForExpiredItemsIfRequired(),因為其內部使用了 Task 進行非同步處理,正確的做法是使用 await this.cache.GetStringAsync("CurrentTime");

1.6 關於快取清理方法 ScanForExpiredItemsIfRequired
        private void ScanForExpiredItemsIfRequired()
        {
            var utcNow = _systemClock.UtcNow;
            if ((utcNow - _lastExpirationScan) > _expiredItemsDeletionInterval)
            {
                _lastExpirationScan = utcNow;
                Task.Run(_deleteExpiredCachedItemsDelegate);
            }
        }

在多執行緒環境下,該方法可能除非多次重複掃描,即可能會多次執行 SQL 語句 DELETE FROM {0} WHERE @UtcNow > ExpiresAtTime ,但是,這也僅僅是警告而已,並沒有任何可改變其行為的控制途徑

1.7 IDistributedCache 的其它擴充套件方法

.Net Core 中還對 IDistributedCache 進行了擴充套件,甚至允許通過 Set 方法傳入一個 DistributedCacheEntryOptions 以覆蓋全域性設定,這些擴充套件方法的使用都比較簡單,直接傳入相應的值即可,在此不再一一介紹
希望深入研究的同學,可以手動逐一測試

1.8 關於 AddDistributedSqlServerCache() 方法

AddDistributedSqlServerCache 方法內部實際上是進行了一系列的註冊操作,其中最重要的是註冊了 SqlServerCache 到 IDistributedCache 介面,該操作使得我們可以在控制器中採用依賴注入的方式使用 IDistributedCache 的例項
檢視 AddDistributedSqlServerCache 方法的程式碼片段

 public static IServiceCollection AddDistributedSqlServerCache(this IServiceCollection services, Action<SqlServerCacheOptions> setupAction)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (setupAction == null)
            {
                throw new ArgumentNullException(nameof(setupAction));
            }

            services.AddOptions();
            AddSqlServerCacheServices(services);
            services.Configure(setupAction);

            return services;
        }

        internal static void AddSqlServerCacheServices(IServiceCollection services)
        {
            services.Add(ServiceDescriptor.Singleton<IDistributedCache, SqlServerCache>());
        }

2. 使用 Redis 分散式快取

要在 Asp.Net Core 專案中使用 Redis 分散式快取,需要引用包:Microsoft.Extensions.Caching.Redis,.Net Core 中的 Redis 分散式快取客戶端由 RedisCache 類提供實現 ,RedisCache 位於程式集 Microsoft.Extensions.Caching.StackExchangeRedis.dll 中,該程式集正是是依賴於大名鼎鼎的 Redis 客戶端 StackExchange.Redis.dll,StackExchange.Redis 有許多的問題,其中最為嚴重的是超時問題,不過這不知本文的討論範圍,如果你希望使用第三方 Redis 客戶端替代 StackExchange.Redis 來使用分散式快取,你需要自己實現 IDistributedCache 介面,好訊息是,IDistributedCache 介面並不複雜,定義非常簡單

2.1 在 Startup.cs 中註冊 Redis 分散式快取配置
    public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedRedisCache(options =>
            {
                options.InstanceName = "TestDb";
                options.Configuration = this.Configuration["RedisConnectionString"];
            });

            ...
        }

註冊 Redis 分散式快取配置和使用 StackExchange.Redis 的方式完全相同,需要注意的是 RedisCacheOptions 包含 3 個屬性,而 Configuration 和 ConfigurationOptions 的作用是相同的,一旦設定了 ConfigurationOptions ,就不應該再去設定屬性 Configuration 的值,因為,在 AddDistributedRedisCache() 註冊內部,會判斷如果設定了 ConfigurationOptions 的值,則不再使用 Configuration;但是,我們建議還是通過屬性 Configuration 去初始化 Redis 客戶端,因為,這是一個連線字串,而各種配置都可以通過連線字串進行設定,這和使用 StackExchange.Redis 的方式是完全一致的

2.2 使用快取
    [Route("api/Home")]
    [ApiController]
    public class HomeController : Controller
    {
        private IDistributedCache cache;
        public HomeController(IDistributedCache cache)
        {
            this.cache = cache;
        }

        [HttpGet("Index")]
        public async Task<ActionResult<string>> SetTime()
        {
            var CurrentTime = DateTime.Now.ToString();
            await this.cache.SetStringAsync("CurrentTime", CurrentTime);
            return CurrentTime;
        }

        [HttpGet("GetTime")]
        public async Task<ActionResult<string>> GetTime()
        {
            var CurrentTime = await this.cache.GetStringAsync("CurrentTime");
            return CurrentTime;
        }
    }

細心的你可能已經發現了,上面的這段程式碼和之前演示的 SqlServerCache 完全一致,是的,僅僅是修改一下注冊的方法,我們就能在專案中進行無縫的切換;但是,對於快取有強依賴的業務,建議還是需要做好快取遷移,確保專案能夠平滑過渡
唯一不同的是,使用 Redis 分散式快取允許你在非同步方法中呼叫同步獲取快取的方法,這不會導致快取清理的問題,因為快取的管理已經完全交給了 Redis 客戶端 StackExchange.Redis 了

3. 實現自定義的分散式快取客戶端,下面的程式碼表示實現一個 CSRedis 客戶端的分散式快取註冊擴充套件

3.1 定義 CSRedisCache 實現 IDistributedCache 介面
    public class CSRedisCache : IDistributedCache, IDisposable
    {
        private CSRedis.CSRedisClient client;
        private CSRedisClientOptions _options;
        public CSRedisCache(IOptions<CSRedisClientOptions> optionsAccessor)
        {
            if (optionsAccessor == null)
            {
                throw new ArgumentNullException(nameof(optionsAccessor));
            }

            _options = optionsAccessor.Value;

            if (_options.NodeRule != null && _options.ConnectionStrings != null)
                client = new CSRedis.CSRedisClient(_options.NodeRule, _options.ConnectionStrings);
            else if (_options.ConnectionString != null)
                client = new CSRedis.CSRedisClient(_options.ConnectionString);
            else
                throw new ArgumentNullException(nameof(_options.ConnectionString));

            RedisHelper.Initialization(client);
        }
        public void Dispose()
        {
            if (client != null)
                client.Dispose();
        }

        public byte[] Get(string key)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            return RedisHelper.Get<byte[]>(key);
        }

        public async Task<byte[]> GetAsync(string key, CancellationToken token = default(CancellationToken))
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            token.ThrowIfCancellationRequested();

            return await RedisHelper.GetAsync<byte[]>(key);
        }

        public void Refresh(string key)
        {
            throw new NotImplementedException();
        }

        public Task RefreshAsync(string key, CancellationToken token = default(CancellationToken))
        {
            throw new NotImplementedException();
        }

        public void Remove(string key)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            RedisHelper.Del(key);
        }

        public async Task RemoveAsync(string key, CancellationToken token = default(CancellationToken))
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            await RedisHelper.DelAsync(key);
        }

        public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            RedisHelper.Set(key, value);
        }

        public async Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken))
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            await RedisHelper.SetAsync(key, value);
        }
    }

程式碼不多,都是實現 IDistributedCache 介面,然後在 IDisposable.Dispose 中釋放資源

3.2 自定義一個配置類 CSRedisClientOptions
    public class CSRedisClientOptions
    {
        public string ConnectionString { get; set; }
        public Func<string, string> NodeRule { get; set; }
        public string[] ConnectionStrings { get; set; }
    }

該配置類主要是為 CSRedis 客戶端接收配置使用

3.3 註冊擴充套件方法 CSRedisCacheServiceCollectionExtensions
 public static class CSRedisCacheServiceCollectionExtensions
    {
        public static IServiceCollection AddCSRedisCache(this IServiceCollection services, Action<CSRedisClientOptions> setupAction)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (setupAction == null)
            {
                throw new ArgumentNullException(nameof(setupAction));
            }

            services.AddOptions();
            services.Configure(setupAction);
            services.Add(ServiceDescriptor.Singleton<IDistributedCache, CSRedisCache>());

            return services;
        }
    }

自定義一個擴充套件方法,進行配置初始化工作,簡化實際註冊使用時的處理步驟

3.4 在 Startup.cs 中使用擴充套件
    public void ConfigureServices(IServiceCollection services)
        {
            services.AddCSRedisCache(options =>
            {
                options.ConnectionString = this.Configuration["RedisConnectionString"];
            });

            ...
        }

上面的程式碼就簡單實現了一個第三方分散式快取客戶端的註冊和使用

3.5 測試自定義分散式快取客戶端,建立一個測試控制器 CustomerController
    [Route("api/Customer")]
    [ApiController]
    public class CustomerController : Controller
    {
        private IDistributedCache cache;
        public CustomerController(IDistributedCache cache)
        {
            this.cache = cache;
        }

        [HttpGet("NewId")]
        public async Task<ActionResult<string>> NewId()
        {
            var id = Guid.NewGuid().ToString("N");
            await this.cache.SetStringAsync("CustomerId", id);
            return id;
        }

        [HttpGet("GetId")]
        public async Task<ActionResult<string>> GetId()
        {
            var id = await this.cache.GetStringAsync("CustomerId");
            return id;
        }
    }

該控制器簡單實現兩個介面,NewId/GetId,執行程式,輸出結果正常

  • 呼叫 NewId 介面建立一條快取記錄

  • 呼叫 GetId 介面獲取快取記錄

至此,我們完整的實現了一個自定義分散式快取客戶端註冊

4. 關於本示例的使用說明

4.1 首先看一下解決方案結構

該解決方案紅框處定義了 3 個不同的 Startup.cs 檔案,分別是

  1. CSRedisStartup (自定義快取測試啟動檔案)
  2. Sql_Startup (SqlServer 測試啟動檔案)
  3. StackChangeRedis_Startup(StackChange.Redis 測試啟動檔案)
  • 在使用本示例的時候,通過在 Program.cs 中切換不同的啟動檔案進行測試
  public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Ron.DistributedCacheDemo.Startups.SqlServer.Startup>();

結束語

通過介紹,我們瞭解到如何在 Asp.Net Core 中使用分散式快取
瞭解了使用不同的快取型別,如 SqlServer 和 Redis
瞭解到瞭如何使用不同的快取型別客戶端進行註冊
瞭解到如何實現自定義快取客戶端
還知道了在呼叫 SqlServer 快取的時候,非同步方法中的同步呼叫會導致 SqlServerCache 無法進行過期掃描
CSRedisCore 此專案是由我的好朋友 nicye 維護,GitHub 倉庫地址:訪問CSRedisCore

示例程式碼下載

https://files.cnblogs.com/files/viter/Ron.DistributedCacheDemo.zip