美文网首页程序员
MemoryCache使用方法

MemoryCache使用方法

作者: sttone | 来源:发表于2019-10-10 16:03 被阅读0次

NuGet Microsoft.Extensions.Caching.Memory

private IMemoryCache _cache;
        //构造器注入
        public CoreMemoryCache(IMemoryCache memoryCache)
        {
            _cache = memoryCache;
        }

Startup 依赖注入

services.AddMemoryCache();

1.创建缓存
set();
创建一个缓存项,可以设置缓存项的绝对和滑动过期时间,优先级等。

 MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
  //绝对过期时间
 cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddMinutes(30);
  //缓存优先级
 cacheExpirationOptions.Priority = CacheItemPriority.Normal;
 cacheExpirationOptions.RegisterPostEvictionCallback(IDGCacheItemChangedHandler, this);
   //添加
   //类似 System.Web.HttpRuntime.Cache[key] 
 _cache.Set(key, value, cacheExpirationOptions);

//根据查询当前key是否存在来判断缓存是否创建成功
  return Exists(key);

MemoryCacheEntryOptions的Priority属性。 Priority属性指定应将哪些对象(基于已设置的优先级)从缓存中删除,作为每当Web服务器内存空间不足时回收内存的运行时策略的一部分。要设置优先级,我们使用CacheItemPriority枚举。这可以具有以下可能的值之一:低,正常,高和NeverRemove

GetOrCreate();
获取或者创建一个缓存,如果缓存存在就获取缓存,不存在就创建缓存

MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddMinutes(30);
cacheExpirationOptions.Priority = CacheItemPriority.Normal;
cacheExpirationOptions.RegisterPostEvictionCallback(IDGCacheItemChangedHandler, this);
   //添加
    //类似 System.Web.HttpRuntime.Cache[key] 
_cache.GetOrCreate(key, ENTRY => { return value; });  
//根据查询当前key是否存在来判断缓存是否创建成功
  return Exists(key);

2.删除缓存

_cache.Remove(key);
//根据查询当前key是否存在来判断缓存是否创建成功
  return Exists(key);

3.修改缓存
没有固定的方法,可先根据key删除(_cache.Remove(key);)缓存,再添加( _cache.Set())缓存

4.获取缓存

_cache.Get(key)

5.验证缓存是否存在

public bool Exists(string key)
        {
            object ReturnValue;
            if (string.IsNullOrEmpty(key))
            {
                return false;
            }
            else
            {
                return _cache.TryGetValue(key, out ReturnValue);
            }
        }

为了便于自己记忆,自己重新编辑了一遍 。参考自:https://www.e-learn.cn/content/net/491137

相关文章

网友评论

    本文标题:MemoryCache使用方法

    本文链接:https://www.haomeiwen.com/subject/gwcapctx.html