Cache_MemoryCache_1简介

1.ASP.NET GitHub地址:https://github.com/aspnet

2.ASP.NET Core缓存 MemoryCache 和 Redis

1.MemoryCache简介

  内存缓存。

  区别:缓存HttpRuntime.Cache 位于System.Web命名空间下。 但是在 ASP.NET Core中System.Web已经不存在。

2.MemoryCacheManager

  

  public class MemoryCacheManager:ICacheManager
  {
    public void Set(string key,object value,TimeSpan cacheTime){
      MemoryCache.Default.Add(key,value,new CacheItemPolicy{SlidingExpireation=cacheTime});
    }
    public T Get<T>(string key){
      return (T)MemoryCache.Default.Get(key);
    }
    public bool Contains(string key){
      return MemoryCache.Default.Contains(key);
    }
    public void Remove(string key){
      MemoryCache.Default.Remove(key);
    }
    public void Clear(){
      foreach(var item in MemoryCache.Default){
      this.Remove(item.Key);
    }
  }

2..为了减少磁盘的读取次数,提高程序性能,将频繁读取的配置文件缓存到内存中,加速配置的读取。并且,在磁盘的配置文件更改后,更新缓存。

//获取内存缓存中的配置字典,如果不存在,读取字典,存入缓存中。

private Dictionary<string,string> GetConfigDictionary(string cacheKey){

  Dictionary<string,string> configs=null;

  ObjectCache cache=MemoryCache.Default;

  if(cache.Contains(cacheKey)){

    return cache.GetCacheItem(cacheKey).Value as Dictionary<string,string>;

  }else{

    configs=GetFormXml();

    //判断是否读取到内容

    if(configs!=null){

      //新建一个策略对象,该对象用于声明配置 对象在缓存中的处理策略

      CacheItemPolicy policy=new CacheItemPolicy();

      //因为配置文件要一直读取,因为在此设置优先级为不删除

      policy.Priority=CacheItemPolicy.NotRemovable;

      //Set方法,会先检查是否存在key ,如果存在,更新value,不存在则创建。

      //这里先加入再加入缓存原因,在缓存加入时,也会触发监视事件,会导致出错。

      cache.Set(cacheKey,configs,policy);

      //新建一个文件监视器对象,添加对资源文件的监视

      List<string> filePaths=new List<string>(){"c:/config.xml"};

      HostFileChangeMonitor monitor=new HostFileChangeMonitor(filePaths);

      //调用监视器的NotifyOnChanged方法,传入发生改变时的回调方法

      monitor.NotifyOnChanged(new OnChangedCallback(o=>{

        cache.Remove(key);

      }));

      policy.ChangeMonitors.Add(monitor);

    }

  }

  return configs;

}

posted @ 2018-05-17 18:07  sujingnuli  阅读(250)  评论(0编辑  收藏  举报