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>();
}
}