Asp.net core 内存缓存的使用

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值