一个.Net Core开源缓存中间件EasyCaching,让你更加简单、方便使用缓存

上次给大家推荐过一个缓存中间件《一个C#开发的非常实用的缓存中间件》,今天再给大家推荐一个缓存中间件,两者功能差不多,都是提供统一接口、多级缓存、分布式缓存、支持多种Provider等。

项目简介

这是一个基于.Net Core开发的缓存中间件,它支持各种缓存并提供了很多高级功能。它的主要目标是让开发人员开发更简单、特别是一些复杂的缓存场景。.

项目特色功能

1、统一缓存接口:方便我们随时调整缓存策略;

2、支持多种缓存:可以满足我们多种业务场景;

3、支持多种缓存系列化:BinaryFormatter、Newtonsoft.Json,MessagePack和Protobuf;

4、支持缓存AOP:able, put,evict,可以简化我们的代码量;

5、多实例支持;

6、支持Diagnostics:方便我们跟踪定位;

7、针对Redis支持特殊Provider:比如原子递增递减的操作等等;

8、二级缓存。

技术架构

1、跨平台:这是基于.Net Core开发的系统,可以部署在Docker, Windows, Linux。

2、基于Net 6.0开发。

3、支持缓存类别:本地缓存:InMemory,SQLite;分布式缓存:StackExchange.Redis,csredis,EnyimMemcachedCore。

项目结构

一个.Net Core开源缓存中间件EasyCaching,让你更加简单、方便使用缓存

 

使用方法

配置缓存

在Startup.cs,配置缓存

public void ConfigureServices(IServiceCollection services){    ......    services.AddEasyCaching(option =>    {        //内存缓存:default        option.UseInMemory("default");        //内存缓存:cus        option.UseInMemory("cus");        //redis缓存:redis1        option.UseRedis(config =>        {            config.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6379));            config.DBConfig.SyncTimeout = 10000;            config.DBConfig.AsyncTimeout = 10000;            config.SerializerName = "mymsgpack";        }, "redis1")        .WithMessagePack("mymsgpack")//with messagepack serialization        ;        //redis缓存:redis2        option.UseRedis(config =>        {            config.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6380));        }, "redis2");        //sqlite缓存        option.UseSQLite(config =>        {            config.DBConfig = new SQLiteDBOptions { FileName = "my.db" };        });        //memcached 缓存        option.UseMemcached(config =>        {            config.DBConfig.AddServer("127.0.0.1", 11211);        });        option.UseMemcached(Configuration);        //fasterKv缓存        option.UseFasterKv(config =>        {            config.SerializerName = "msg";        })            .WithMessagePack("msg");    });}

使用方式

 

public class CusController : Controller{ //缓存 private readonly IEasyCachingProviderFactory _factory; public CusController(IEasyCachingProviderFactory factory) { this._factory = factory; }
// GET api/cus/inmem?name=Default [HttpGet] [Route("inmem")] public string Get(string name = EasyCachingConstValue.DefaultInMemoryName) { //根据name,获取缓存实例 var provider = _factory.GetCachingProvider(name); var val = name.Equals("cus") ? "cus" : "default"; var res = provider.Get("demo", () => val, TimeSpan.FromMinutes(1)); return $"cached value : {res}"; } ......}

ResponseCache缓存

[ResponseCache(Duration = 30, VaryByQueryKeys = new string[] { "page" })]public IActionResult List(int page = 0){return Content(page.ToString());}

AOP缓存

[EasyCachingAble(Expiration = 10)]string GetCurrentUtcTime();[EasyCachingPut(CacheKeyPrefix = "Castle")]string PutSomething(string str);[EasyCachingEvict(IsBefore = true)]void DeleteSomething(int id);
 

项目地址

https://github.com/dotnetcore/EasyCaching