ASP.NET Core 使用 Redis 實現分布式緩存:Docker、IDistributedCache、StackExchangeRedis
前提:一台 Linux 服務器、已安裝 Docker。
一,Docker 中運行 Redis
拉取 Redis 鏡像
docker pull redis
查詢鏡像列表
docker imgaes
運行 Redis的幾種方法
①運行並且設置 Redis 端口
docker run -p 6379:6379 -d redis:latest redis-server
②
docker run -p 6379:6379 -d {鏡像id} redis-server
③持久化
將 Docker 里的 Redis 數據持久化到物理機
docker run -p 6379:6379 -v {物理機路徑}:/data -d redis:latest redis-server --appendonly yes
下載 Windows 版的 Redis 管理器
Windows 版本的 Redis Desktop Manager 64位 2019.1(中文版) 下載地址 https://www.7down.com/soft/233274.html
官方正版最新版本下載地址 https://redisdesktop.com/download
另附 Redis 學習教程:
Redis 中文網 https://www.redis.net.cn/
.NET 使用 Redis 學習 地址(貌似這個教程版本過時了) https://www.cnblogs.com/cang12138/p/8884362.html
搭建 Master/Slaver 模式的 Redis 集群 https://blog.csdn.net/lupengfei1009/article/details/88323561#_154
使用 Redis Desktop Manager 連接 Redis
二,ASP.NET Core 使用分布式緩存
ASP.NET Core 中,支持使用多種數據庫進行緩存,ASP.NET Core 提供了統一的接口給開發者使用。
IDistributedCache
ASP.NET Core 中,使用 IDistributedCache 為開發者提供統一的緩存使用接口,而不必關注使用的是何種數據庫。
IDistributedCache]接口提供了以下方法操作的分布式的緩存實現中的項:
- GetAsync –接受字符串鍵和檢索緩存的項作為
byte[]
數組如果在緩存中找到。 - SetAsync –中添加項 (作為
byte[]
數組) 到使用字符串鍵的緩存。 - RefreshAsync –刷新緩存基於其密鑰,重置其滑動到期超時值 (如果有) 中的項。
- RemoveAsync –移除緩存項根據其字符串鍵值。
IDistributedCache 提供的常用方法如下:
方法 | 說明 |
---|---|
Get(String) | 獲取Key(鍵)的值 |
GetAsync(String, CancellationToken) | 異步獲取鍵的值 |
Refresh(String) | 刷新緩存 |
RefreshAsync(String, CancellationToken) | Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any). |
Remove(String) | 移除某個值 |
RemoveAsync(String, CancellationToken) | Removes the value with the given key. |
[Set(String, Byte], DistributedCacheEntryOptions) | Sets a value with the given key. |
[SetAsync(String, Byte], DistributedCacheEntryOptions, CancellationToken) | Sets the value with the given key. |
官方文檔很詳細https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.extensions.caching.distributed.idistributedcache?view=aspnetcore-2.2
ASP.NET Core 中配置緩存
新建一個 ASP.NET Core WebApi 項目
Nuget 管理器安裝
Microsoft.Extensions.Caching.StackExchangeRedis
ConfigureServices 中使用服務
services.AddDistributedMemoryCache();
配置 Redis 服務器
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost:6379";
options.InstanceName = "mvc";
});
InstanceName 是你自定義的實例名稱,創建緩存時會以此名稱開頭。
這樣就配置好了。
使用緩存
修改默認生成的 ValuesController.cs。
注入緩存服務
private readonly IDistributedCache _cache;
public ValuesController(IDistributedCache cache)
{
_cache = cache;
}
設置緩存和使用緩存:
await _cache.GetAsync("{鍵名}");
_cache.SetAsync("鍵名", {值}, {設置});
刪除原來的方法,添加以下代碼:
[HttpGet("Set")]
public async Task<JsonResult> SetCache(string setkey, string setvalue)
{
string key = "key1";
if (!string.IsNullOrEmpty(setkey))
key = setkey;
string value = DateTime.Now.ToLongTimeString();
if (!string.IsNullOrEmpty(setvalue))
value = setvalue;
await _cache.SetStringAsync(key, value);
return new JsonResult(new { Code = 200, Message = "設置緩存成功", Data = "key=" + key + " value=" + value });
}
[HttpGet("Get")]
public async Task<JsonResult> GetCache(string setkey)
{
string key = "key1";
if (!string.IsNullOrEmpty(setkey))
key = setkey;
var value = await _cache.GetStringAsync(key);
return new JsonResult(new { Code = 200, Message = "設置緩存成功", Data = "key=" + key + " value=" + value });
}
在 URL 添加 QueryString 可以設置緩存內容,如果沒有帶參數的話,就使用默認的值。
打開 https://localhost:5001/api/values/set 可以看到設置了默認值。
或者訪問 https://localhost:5001/api/values/set?setkey=key11111&setvalue=asafesfdsreg
自定義設置緩存值。
打開 https://localhost:5001/api/values/get?setkey=key11111
可以獲取緩存值。
設置緩存過期時間
使用 DistributedCacheEntryOptions 可以設置緩存過期時間
DistributedCacheEntryOptions 有三個屬性,表示相對時間、絕對時間。
使用方法
[HttpGet("Set")]
public async Task<JsonResult> SetCache(string setkey, string setvalue)
{
string key = "key1";
if (!string.IsNullOrEmpty(setkey))
key = setkey;
string value = DateTime.Now.ToLongTimeString();
if (!string.IsNullOrEmpty(setvalue))
value = setvalue;
var options = new DistributedCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromSeconds(20));
await _cache.SetStringAsync(key, value, options);
return new JsonResult(new { Code = 200, Message = "設置緩存成功", Data = "key=" + key + " value=" + value });
}
緩存 20 秒,20秒過后此緩存將被清除。