NET CORE 3.1 IMemoryCache

services.AddMemoryCache();

        public class user
        {
            public string Name { get; set; }
            public string password { get; set; }
        }
        public void Create(string name)
        {
            var list = new List<user>();
            list.Add(new user() { Name = "lfh", password = "123456" });
            list.Add(new user() { Name = "cw", password = "Q23456" });

            _cache.Set("re_" + name, list, 
                new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove));


            var b = _cache.GetOrCreate("re_" + name, entity => {
                entity.SetPriority(CacheItemPriority.NeverRemove);
                return list;
            });
        }

        public ActionResult Get(string name)
        {
            var a = _cache.Get("re_" + name);
            return Ok( a);
        }
        //删除
        public void Delete(string name)
        {
            _cache.Remove("re_" + name);
        }

        public ActionResult CreateReturn(string name)
        {
            var re = "6AE017A7-9FE8-44A0-BC39-5A5D76D273BB";

            var b = _cache.GetOrCreate("re_" + name, entity => {
                entity.SetPriority(CacheItemPriority.NeverRemove);
                entity.RegisterPostEvictionCallback(callback: MyCallback, state: this);
                return re;
            });
            return Ok(b);
        }
        private static void MyCallback(object key, object value, EvictionReason reason, object state)
        {
            var message = $"Cache entry was removed : {reason}"; ((HomeController)state).
           _cache.Set("callbackMessage", message);
        }

猜你喜欢

转载自www.cnblogs.com/LiuFengH/p/13177002.html