.NET Core Cache [MemoryCache]

参考资料:long0801的博客

添加对Microsoft.Extensions.Caching.Memory命名空间的引用,它提供了.NET Core默认实现的MemoryCache类,以及全新的内存缓存API

代码如下:

using System;
using Microsoft.Extensions.Caching.Memory;

namespace FrameWork.Common.DotNetCache
{
    public class CacheHelper
    {
        static readonly MemoryCache Cache = new MemoryCache(new MemoryCacheOptions());

        /// <summary>
        /// 获取缓存中的值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static object GetCacheValue(string key)
        {
            if ( !string.IsNullOrEmpty(key) && Cache.TryGetValue(key, out var val))
            {
                return val;
            }
            return default(object);
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetCacheValue(string key, object value)
        {
            if (!string.IsNullOrEmpty(key))
            {
                Cache.Set(key, value, new MemoryCacheEntryOptions
                {
                    SlidingExpiration = TimeSpan.FromHours(1)
                });
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/dawenyang/p/9224277.html