program.cs中加入
builder.Services.AddMemoryCache();
controller中注入
//[ResponseCache(Duration =20)]
[Route("[controller]")]
public class GetPatientTop10Controller : Controller
{
private readonly IMemoryCache _memoryCache;
public GetPatientTop10Controller(IMemoryCache memoryCache)
{
this._memoryCache = memoryCache;
}
[HttpGet(Name = "GetPatientByTop")]
public IEnumerable<PatientModel> Get(string DispensingDate)
{
return MyDB.Patient.GetPatientListtop10(DispensingDate).AsEnumerable<PatientModel>();
}
[HttpGet(Name = "GetPatientByTop1")]
public async Task<ActionResult<PatientModel>> GetByID(long id)
{
//ID必须设置防止数据混乱
PatientModel? pm = await _memoryCache.GetOrCreateAsync("Patient" + id, async (e) =>
{
e.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(Random.Shared.Next(30,60));// 缓存有效期30-60秒,随机值防止集中过期导致雪崩
e.SlidingExpiration = TimeSpan.FromSeconds(30); //缓存滑动有效期30秒
return await MyDB.Patient.GetPatientByID(id);
});
return pm;
//return MyDB.Patient.GetPatientListtop10(DispensingDate).AsEnumerable<PatientModel>();
}
}
本文介绍了一个使用.NET Core内置的IMemoryCache实现缓存优化的例子。通过在GetPatientTop10Controller控制器中注入IMemoryCache服务,并利用GetOrCreateAsync方法来缓存PatientModel对象,有效提升了数据访问效率并减少了数据库负担。
603

被折叠的 条评论
为什么被折叠?



