内存缓存
Zack.ASPNETCore
封装了哪些功能
1)缓存禁止了IQueryable、IEnumerable这两种类型
IQueryable、IEnumerable等类型可能存在着延迟加载的问题,如果把这两种类型的变量指向的对象保存到缓存中,在我们把它们取出来再去执行的时候,如果它们延迟加载时候需要的对象已经被释放的话,就会执行失败
2)实现随机缓存过期时间
1、在Program.cs中注册封装的内存缓存服务
接口和实现类都封装好了,不需要自己写
builder.Services.AddScoped<IMemoryCacheHelper, MemoryCacheHelper>();
2、在控制器中注入封装的内存缓存服务
private readonly IMemoryCacheHelper memoryCacheHelper;
public TestController(IMemoryCacheHelper memoryCacheHelper) {
this.memoryCacheHelper = memoryCacheHelper;
}
3、在控制器方法中读取缓存数据
var b=await memoryCacheHelper.GetOrCreateAsync("Book" + id, async (e) => {
return await MyDbContext.GetByIdAsync(id);
}, 10);
注意事项
- 1)设置10,实际是10-20s之间(框架实现的),原理很简单,就是将绝对过期时间设为了10-20之间
- 2)是10-20s之间随机double过期时间,因为int不能平均分配到时间轴
- 3)但是不确定设置绝对过期时间后是否会生效,不知道他和框架的哪个先执行,所以如果就是需要设置固定的过期时间,不要用此框架!
分布式缓存
Zack.ASPNETCore
封装的功能
- 解决缓存穿透、缓存雪崩等问题
- 自动地进行其他类型的转换
1、在Program.cs中注册封装的分布式缓存服务
builder.Services.AddScoped<IDistributedCacheHelper, DistributedCacheHelper>();
2、在控制器中注入封装的分布式缓存服务
private readonly IDistributedCacheHelper distributedCacheHelper;
public TestController(IDistributedCacheHelper distributedCacheHelper) {
this.distributedCacheHelper = distributedCacheHelper;
}
3、在控制器方法中读取缓存数据
//默认采用绝对过期时间,下面设置了绝对过期时间20s
var book=await distributedCacheHelper.GetOrCreateAsync("Book" + id, async(e) => {
//设置滑动过期时间5s,这样会和绝对过期时间20s混用
e.SlidingExpiration = TimeSpan.FromSeconds(5);
var book = await MyDbContext.GetByIdAsync(id);
return book;
},20);