.net core中使用缓存(cache)

官方文档:https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-2.2#use-setsize-size-and-sizelimit-to-limit-cache-size

在类中(不是controller)中使用的时候可以使用这个:

private static MemoryCache cache = new MemoryCache(new MemoryCacheOptions()); //定义cache
        public static object GetCacheValue(string key)//获取值
        {
            object val = null;
            if (key != null && cache.TryGetValue(key, out val))
            {
                return val;  
            }
            else
            {
                return default(object);
            }
        }
        public static void SetChacheValue(string key, object value)//设置值
        {
            if (key != null)
            {
                cache.Set(key, value, new MemoryCacheEntryOptions
                {
                    SlidingExpiration = TimeSpan.FromSeconds(10)
                });
            }
        }

猜你喜欢

转载自www.cnblogs.com/fishyues/p/10278573.html