编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

EasyCaching——超级强大的开源缓存库

wxchong 2024-08-24 01:53:00 开源技术 10 ℃ 0 评论


EasyCaching

EasyCaching 是一个开源的缓存库,包含了缓存的基本用法和一些高级用法,可以帮助我们更轻松地处理缓存!支持 内存缓存,Redis,CSRedis,Memcached,SQLite 缓存 ,磁盘缓存,LiteDB 缓存FasterKv (混合内存和磁盘),只需要引用相对应得包即可

在Memory的使用

  1. 1. 通过 Nuget 安装包

Install-Package EasyCaching.InMemory

  1. 1. Startup 类中的配置 有两种方法可以配置缓存提供程序。

通过 C# 代码:

public class Startup
{
//...

public void ConfigureServices(IServiceCollection services)
{
//other services.

//Important step for In-Memory Caching
services.AddEasyCaching(options =>
{
// use memory cache with a simple way
options.UseInMemory("default");

// use memory cache with your own configuration
options.UseInMemory(config =>
{
config.DBConfig = new InMemoryCachingOptions
{
// scan time, default value is 60s
ExpirationScanFrequency = 60,
// total count of cache items, default value is 10000
SizeLimit = 100,

// below two settings are added in v0.8.0
// enable deep clone when reading object from cache or not, default value is true.
EnableReadDeepClone = true,
// enable deep clone when writing object to cache or not, default value is false.
EnableWriteDeepClone = false,
};
// the max random second will be added to cache's expiration, default value is 120
config.MaxRdSecond = 120;
// whether enable logging, default is false
config.EnableLogging = false;
// mutex key's alive time(ms), default is 5000
config.LockMs = 5000;
// when mutex key alive, it will sleep some time, default is 300
config.SleepMs = 300;
}, "default1");
});
}
}

或者,您可以将配置存储在 .appsettings.json

public class Startup
{
//...

public void ConfigureServices(IServiceCollection services)
{
//other services.

//Important step for In-Memory Caching
services.AddEasyCaching(options =>
{
//use memory cache
options.UseInMemory(Configuration, "default", "easycaching:inmemory");
});
}
}
  1. 1. 调用 EasyCachingProvider 以下代码演示如何在 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));

//Get
var res = _provider.Get("demo", () => "456", TimeSpan.FromMinutes(1));

//Get without data retriever
var res = _provider.Get<string>("demo");

//Remove Async
await _provider.RemoveAsync("demo");

//Set Async
await _provider.SetAsync("demo", "123", TimeSpan.FromMinutes(1));

//Get Async
var res = await _provider.GetAsync("demo",async () => await Task.FromResult("456"), TimeSpan.FromMinutes(1));

//Get without data retriever Async
var res = await _provider.GetAsync<string>("demo");
}
}

项目地址

https://easycaching.readthedocs.io/




Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表