.net中数据缓存使用

今天 遇到一个问题 访问一个接口数据 基本上是固定的,于是想把数据 缓存下来。。。于是版本1 诞生了

private static ConcurrentDictionary<int, List<xxxxx>> xxxxCache = new ConcurrentDictionary<int, List<xxxxx>>();

private List<xxxxx> GetXXXByCache(int id)
        {
            if (!xxxxCache.ContainsKey(Id))
            {
                var list = xxxxService.GetxxxxList(Id);
                xxxxCache.TryAdd(Id, list);
            }
            return xxxxxCache[Id];
        }

跑起来没问题 然后 突然想到 一个问题 如果 接口数据变化 怎么办。。。。。。。于是想加了 缓存时间 发现 自己实现还要存过期时间 有点复杂 查查资料 发现net4.0有个 ObjectCache 于是 2.0 诞生了 

 private static ObjectCache DealerCache = MemoryCache.Default;       

private List<xxxxx> GetxxxByCache(int Id)
        {
            var cachekey = "xxxlist_" + Id;
            var ret = Cache.Get(cachekey) as List<xxxx>;
            if (ret == null)
            {
                ret = _xxxxService.GetxxxxList(Id);
                var policy = new CacheItemPolicy() { AbsoluteExpiration = DateTime.Now.AddMinutes(10) };
                Cache.Set("list_" + Id, ret, policy);
            }
            return ret;
        }

 

相关资料 :

http://www.cnblogs.com/TianFang/p/3430169.html

posted @ 2016-05-26 16:02  沐松  阅读(555)  评论(0编辑  收藏  举报