.NET CORE下的Cache

.NET CORE 下的缓存跟之前ASP.NET下的缓存有所不同,应用.NET CORE缓存首先需要引入Microsoft.Extensions.Caching.Memory程序包

下面简单写了一个CacheHelper类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Microsoft.Extensions.Caching.Memory;

namespace Common
{
    public class CacheHelper
    {
        private static MemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions());
        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="minutes">缓存有效时间</param>
        public static void Add(string key, object value, int minutes)
        {            
            memoryCache.Set(key, value, new TimeSpan(0, minutes, 0));            
        }

        /// <summary>
        /// 获取缓存值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static object GetValue(string key)
        {
            object value = null;
            memoryCache.TryGetValue(key, out value);
            return value;
        }


        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="key"></param>
        public static void Remove(string key)
        {
            memoryCache.Remove(key);
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/pudefu/p/10687957.html