ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

.net core3.1中使用缓存MemoryCache

2021-04-06 14:34:57  阅读:398  来源: 互联网

标签:缓存 string MemoryCache cache key core3.1 new net public


nugt包依赖:

  • 1.Microsoft.Extensions.Caching.Abstractions
  • 2.Microsoft.Extensions.Caching.Memory

封装的帮助类

添加类库Snblog.Cache

新建文件 Cache

新建帮助类 CacheManager.cs

using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace Snblog.Cache.Cache
{
 public class CacheManager
    {
        public static CacheManager Default = new CacheManager();
        public  TimeSpan time = new TimeSpan(00, 00, 01, 0); //缓存过期时间
        private IMemoryCache _cache = new MemoryCache(new MemoryCacheOptions());

        /// <summary>
        /// 判断是否在缓存中
        /// </summary>
        /// <param name="key">关键字</param>
        /// <returns></returns>
        public bool IsInCache(string key)
        {
            List<string> keys = GetAllKeys();
            foreach (var i in keys)
            {
                if (i == key) return true;
            }
            return false;
        }

        /// <summary>
        /// 获取所有缓存键
        /// </summary>
        /// <returns></returns>
        public List<string> GetAllKeys()
        {
            const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
            var entries = _cache.GetType().GetField("_entries", flags).GetValue(_cache);
            var cacheItems = entries as IDictionary;
            var keys = new List<string>();
            if (cacheItems == null) return keys;
            foreach (DictionaryEntry cacheItem in cacheItems)
            {
                keys.Add(cacheItem.Key.ToString());
            }
            return keys;
        }

        /// <summary>
        /// 获取所有的缓存值
        /// </summary>
        /// <returns></returns>
        public List<T> GetAllValues<T>()
        {
            var cacheKeys = GetAllKeys();
            List<T> vals = new List<T>();
            cacheKeys.ForEach(i =>
            {
                T t;
                if (_cache.TryGetValue<T>(i, out t))
                {
                    vals.Add(t);
                }
            });
            return vals;
        }
        /// <summary>
        /// 取得缓存数据
        /// </summary>
        /// <typeparam name="T">类型值</typeparam>
        /// <param name="key">关键字</param>
        /// <returns></returns>
        public T Get<T>(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));
            T value;
            _cache.TryGetValue<T>(key, out value);
            return value;
        }

        /// <summary>
        /// 设置缓存(永不过期)
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="value">缓存值</param>
        public void Set_NotExpire<T>(string key, T value)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            T v;
            if (_cache.TryGetValue(key, out v))
                _cache.Remove(key);
            _cache.Set(key, value);
        }

        /// <summary>
        /// 设置缓存(滑动过期:超过一段时间不访问就会过期,一直访问就一直不过期)
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="value">缓存值</param>
        public void Set_SlidingExpire<T>(string key, T value, TimeSpan span)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            T v;
            if (_cache.TryGetValue(key, out v))
                _cache.Remove(key);
            _cache.Set(key, value, new MemoryCacheEntryOptions()
            {
                SlidingExpiration = span
            });
        }

        /// <summary>
        /// 设置缓存(绝对时间过期:从缓存开始持续指定的时间段后就过期,无论有没有持续的访问)
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="value">缓存值</param>
        public void Set_AbsoluteExpire<T>(string key, T value, TimeSpan span)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            T v;
            if (_cache.TryGetValue(key, out v))
                _cache.Remove(key);
            _cache.Set(key, value, span);
        }

        /// <summary>
        /// 设置缓存(绝对时间过期+滑动过期:比如滑动过期设置半小时,绝对过期时间设置2个小时,那么缓存开始后只要半小时内没有访问就会立马过期,如果半小时内有访问就会向后顺延半小时,但最多只能缓存2个小时)
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="value">缓存值</param>
        /// <param name="slidingSpan"></param>
        /// <param name="absoluteSpan"></param>
        public void Set_SlidingAndAbsoluteExpire<T>(string key, T value, TimeSpan slidingSpan, TimeSpan absoluteSpan)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            T v;
            if (_cache.TryGetValue(key, out v))
                _cache.Remove(key);
            _cache.Set(key, value, new MemoryCacheEntryOptions()
            {
                SlidingExpiration = slidingSpan,
                AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(absoluteSpan.Milliseconds)
            });
        }

        /// <summary>
        /// 移除缓存
        /// </summary>
        /// <param name="key">关键字</param>
        public void Remove(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            _cache.Remove(key);
        }

        /// <summary>
        /// 释放
        /// </summary>
        public void Dispose()
        {
            if (_cache != null)
                _cache.Dispose();
            GC.SuppressFinalize(this);
        }
    }

}

Service中使用

        //创建内存缓存对象
        private static CacheManager _cache = new CacheManager();
        
         /// <summary>
        /// 返回总条数
        /// </summary>
        /// <returns></returns>
        public int GetArticleCount()
        {
            int result;
            if (_cache.IsInCache("GetArticleCount")) //是否存在缓存
            {
                result = _cache.Get<int>("GetArticleCount");//读缓存值
                if (result <= 0)
                {
                    _cache.Set_AbsoluteExpire("GetArticleCount", CreateService<SnArticle>().Count(), _cache.time);//设置缓存
                    result = _cache.Get<int>("GetArticleCount");
                }
            }
            else
            {
                _cache.Set_AbsoluteExpire("GetArticleCount", CreateService<SnArticle>().Count(), _cache.time); //设置缓存
                result = _cache.Get<int>("GetArticleCount");
            }
            return result;
        }
        
        

标签:缓存,string,MemoryCache,cache,key,core3.1,new,net,public
来源: https://www.cnblogs.com/ouyangkai/p/14621709.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有