簡介
做后端開發,緩存應該是天天在用,很多時候我們的做法是寫個幫助類,然后用到的時候調用一下。這種只適合簡單層次的應用;一旦涉及到接口實現調整之類的,這種強耦合的做法很不合適。有些其他的功能又要去重復造輪子。下面我們介紹下EasyCaching。
github地址
EasyCaching 是一個開源緩存庫,包含緩存的基本用法和一些高級用法,可以幫助我們更輕松地處理緩存!
主要功能
統一的抽象緩存接口
多種常用的緩存Provider(InMemory,Redis,Memcached,SQLite)
為分布式緩存的數據序列化提供了多種選擇
二級緩存
緩存的AOP操作(able, put,evict)
多實例支持
支持Diagnostics
Redis的特殊Provider
EasyCaching.Redis 是一個基于EasyCaching.Core和StackExchange.Redis的 redis 緩存庫。
當你使用這個庫時,這意味著你將處理你的 redis 服務器的數據。像往常一樣,我們將它用作分布式緩存。
如何使用
基本用法
1.通過Nuget安裝包
Install-Package EasyCaching.Redis復制代碼
2. Startup 類中的配置
有兩種方法可以配置緩存提供程序。
通過 C# 代碼:
public class Startup{ //...public void ConfigureServices(IServiceCollection services){ //other services.//Important step for Redis Caching services.AddEasyCaching(option =>{option.UseRedis(config => {config.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6379));}, "redis1");});}
}復制代碼
或者,您可以將配置存儲在appsettings.json
.
public class Startup{ //...public void ConfigureServices(IServiceCollection services){ //other services.//Important step for Redis Cachingservices.AddEasyCaching(option =>{option.UseRedis(Configuration, "myredisname");});}
}復制代碼
appsettings.json
例子:
"easycaching": { "redis": { "MaxRdSecond": 120, "EnableLogging": false, "LockMs": 5000, "SleepMs": 300, "dbconfig": { "Password": null, "IsSsl": false, "SslHost": null, "ConnectionTimeout": 5000, "AllowAdmin": true, "Endpoints": [{ "Host": "localhost", "Port": 6739}], "Database": 0}}
}復制代碼
3.調用IEasyCachingProvider
以下代碼展示了如何在 ASP.NET Core Web API 中使用 EasyCachingProvider。
[Route("api/[controller]")]public class ValuesController : Controller{ private readonly IEasyCachingProvider _provider; public ValuesController(IEasyCachingProvider provider){ this._provider = provider;}[HttpGet] public string Get(){ //Remove_provider.Remove("demo"); //Set_provider.Set("demo", "123", TimeSpan.FromMinutes(1)); //others ...}
}復制代碼
4. Redis 功能提供者
Redis還有很多其他的數據類型,比如Hash、List等。
EasyCaching.Redis 也支持那些命名為 redis 特性提供者的類型。
如果您想使用此功能提供程序,只需調用IRedisCachingProvider
replace 即可IEasyCachingProvider
。
[Route("api/[controller]")]public class ValuesController : Controller{ private readonly IRedisCachingProvider _provider; public ValuesController(IRedisCachingProvider provider){ this._provider = provider;}[HttpGet] public string Get(){ // HMSetvar res = _provider.HMSet(cacheKey, new Dictionary<string, string>{{"a1","v1"},{"a2","v2"}}); //others ...}
}