IDistributedCache 介紹
C# 提供的這個Interface主要是讓我們用來操作各種不同的快取服務,可以適用的有以下幾種:
以下說明都以Redis爲主。
註冊 IDistributedCache
透過呼叫 AddStackExchangeRedisCache 來進行Redis的配置
csharpbuilder.Services.AddStackExchangeRedisCache(options => { options.Configuration = builder.Configuration.GetConnectionString("RedisConnectString"); options.InstanceName = "MyFirstRedis"; // 這行主要的目的爲在往後的Redis儲存都會加上"MyFisrtRedis"前綴字,可以方便的在Redis區分出是哪個應用的Cache。 });
Cache 的基本操作
- 取得cache
| 方法名稱 | 參數 | 回傳類型 |
|---|---|---|
| Get | String | byte[]? |
| GetAsync | String CalcellationToken | byte[]? |
| GetString | IDistributedCache String | string? |
| GetStringAsync | IDistributedCache String CancellationToken | string? |
要特別注意的是這兩個方法回傳的類別,Get、GetAsync回傳的byte,而GetString、GetStringAsync回傳的是String。
csharp_cache.Get("users:1"); _cache.GetAsync("users:1", ct); _cache.GetString("users:1"); _cache.GetStringAsync("users:1");
- 設置cache
| 方法名稱 | 參數 | 回傳類型 |
|---|---|---|
| Set | IDistributedCache String Byte[] | void |
| SetAsync | IDistributedCache String Byte[] CancellationToken | void |
| SetString | IDistributedCache String String DistributedCacheEntryOptions | void |
| SetString | IDistributedCache String String | void |
| SetStringAsync | IDistributedCache String String CancellationToken | void |
| SetStringAsync | IDistributedCache String String DistributedCacheEntryOptions CancellationToken | void |
設置的方法會稍微複雜點,因爲牽扯到了是否要設定到期日的問題,要設定到期的日期就得先提到 DistributedCacheEntryOptions。
DistributedCacheEntryOptions用法如下:
csharpvar options = new DistributedCacheEntryOptins { // 設定絕對過期的時間 AbsoluteExpiration = new DateTimeOffset(new DateTime(2026, 12, 31, 23, 59, 59)) // 相對現在時間的過期時間 AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1) // 滑動過期時間,20分鐘內有人讀取就會自動再次延長20分鐘 SlidingExpiration = TimeSpan.FromMinutes(20) }; // 上述可以進行組合。
接着我們來看如何設置Cache。
csharpstring originValue = "users1value"; byte[] byteValue = Encoding.UTF8.GetBytes(originValue); var options = new DistributedCacheEntryOptins { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1) }; _cache.Set("users1", byteValue); _cache.SetAsync("users1", byteValue); _cache.SetString("users1", originValue, options); _cache.SetString("users1", originValue); _cache.SetStringAsync("users1", originValue, ct); _cache.SetStringAsync("users1", originValue, options, ct);
Redis中如果沒有傳入options通常代表不會過期。