Step 1. 首先我們需要安裝 Microsoft.Extensions.Caching.StackExchangeRedis 套件。 開啟 工具 > NuGet 套件管理員 > 管理方案的 NuGet 套件
Step 2. 搜尋 StackExchangeRedis > 選擇 Microsoft.Extensions.Caching.StackExchangeRedis 套件 > 勾選專案並安裝
Step 3. 開啟 Startup.cs,在 ConfigureServices 方法內加上下列語法。其中 options.Configuration 為你的 Redis 連線字串。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddStackExchangeRedisCache(options => | |
{ | |
options.InstanceName = ""; | |
options.Configuration = "RedisCacheDemo.redis.cache.windows.net:6380,password=password,ssl=True,abortConnect=False"; | |
}); | |
} |
Step 4. 接下來,你可以在 Controller 或 Services 內做建構子注入,即可開始使用 Redis Cache。如下 public async Task<string> Get() 方法內,即是一個簡單的 Cache 使用範例。
1. 先從 Cache 取得資料
2. 若 Cache 有資料,則直接回傳資料
2. 若 Cache 沒有資料,則設定 Cache (一般情況,從資料庫取得資料再設定 Cache)
3. 完成設定快取後,回傳資料
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class HomeController : Controller | |
{ | |
private readonly IDistributedCache _cache; | |
public HomeController(IDistributedCache cache) | |
{ | |
_cache = cache; | |
} | |
// GET api/values | |
[HttpGet] | |
public async Task<string> Get() | |
{ | |
var key = "key"; | |
var valueByte = await _cache.GetAsync(key); | |
if (valueByte == null) | |
{ | |
await _cache.SetAsync(key, Encoding.UTF8.GetBytes("value"), new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(3000))); | |
valueByte = await _cache.GetAsync(key); | |
} | |
var valueString = Encoding.UTF8.GetString(valueByte); | |
return valueString; | |
} | |
} |
2 留言
網誌管理員已經移除這則留言。
回覆刪除一般來說 Redis 有不同的資料庫,用 IDistributedCache 的話要怎麼選擇不同資料庫呢
回覆刪除