avatar

C# IDistributedCache

IDistributedCache 介紹

C# 提供的這個Interface主要是讓我們用來操作各種不同的快取服務,可以適用的有以下幾種:

以下說明都以Redis爲主。

註冊 IDistributedCache

透過呼叫 AddStackExchangeRedisCache 來進行Redis的配置

csharp
builder.Services.AddStackExchangeRedisCache(options => { options.Configuration = builder.Configuration.GetConnectionString("RedisConnectString"); options.InstanceName = "MyFirstRedis"; // 這行主要的目的爲在往後的Redis儲存都會加上"MyFisrtRedis"前綴字,可以方便的在Redis區分出是哪個應用的Cache。 });

Cache 的基本操作

  • 取得cache
方法名稱參數回傳類型
GetStringbyte[]?
GetAsyncString
CalcellationToken
byte[]?
GetStringIDistributedCache
String
string?
GetStringAsyncIDistributedCache
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
方法名稱參數回傳類型
SetIDistributedCache
String
Byte[]
void
SetAsyncIDistributedCache
String
Byte[]
CancellationToken
void
SetStringIDistributedCache
String
String
DistributedCacheEntryOptions
void
SetStringIDistributedCache
String
String
void
SetStringAsyncIDistributedCache
String
String
CancellationToken
void
SetStringAsyncIDistributedCache
String
String
DistributedCacheEntryOptions
CancellationToken
void

設置的方法會稍微複雜點,因爲牽扯到了是否要設定到期日的問題,要設定到期的日期就得先提到 DistributedCacheEntryOptions

DistributedCacheEntryOptions用法如下:

csharp
var 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。

csharp
string 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通常代表不會過期。

C# IDistributedCache | SIC 個人網站