基于MemoryCache的缓存辅助类
2017-01-06 13:50
162 查看
背景:
1. 什么是MemoryCache?
memoryCache就是用电脑内存做缓存处理
2.使用范围?
可用于不常变的数据,进行保存在内存中,提高处理效率
代码:
1. 什么是MemoryCache?
memoryCache就是用电脑内存做缓存处理
2.使用范围?
可用于不常变的数据,进行保存在内存中,提高处理效率
代码:
/// <summary> /// 基于MemoryCache的缓存辅助类 /// </summary> public static class MemoryCacheHelper { private static readonly Object _locker = new object(); public static T GetCacheItem<T>(String key, Func<T> cachePopulate, TimeSpan? slidingExpiration = null, DateTime? absoluteExpiration = null) { if (String.IsNullOrWhiteSpace(key)) throw new ArgumentException("Invalid cache key"); if (cachePopulate == null) throw new ArgumentNullException("cachePopulate"); if (slidingExpiration == null && absoluteExpiration == null) throw new ArgumentException("Either a sliding expiration or absolute must be provided"); if (MemoryCache.Default[key] == null) { lock (_locker) { if (MemoryCache.Default[key] == null) { var item = new CacheItem(key, cachePopulate()); var policy = CreatePolicy(slidingExpiration, absoluteExpiration); MemoryCache.Default.Add(item, policy); } } } return (T)MemoryCache.Default[key]; } private static CacheItemPolicy CreatePolicy(TimeSpan? slidingExpiration, DateTime? absoluteExpiration) { var policy = new CacheItemPolicy(); if (absoluteExpiration.HasValue) { policy.AbsoluteExpiration = absoluteExpiration.Value; } else if (slidingExpiration.HasValue) { policy.SlidingExpiration = slidingExpiration.Value; } policy.Priority = CacheItemPriority.Default; return policy; } }
相关文章推荐
- K-means聚类算法
- 十张图看懂未来的大数据世界
- AsyncTask 串行还是并行
- 切换npm源
- hibernate多对多关联映射
- 小明的烦恼
- 探索Lua5.2内部实现:Garbage Collection(3)
- Python练习实例9
- C#委托的介绍(delegate、Action、Func、predicate)
- Yii2.0-advanced-6—联表查询加搜索分页
- Spring MVC 完美解决跨域问题
- 【计算机网络】TCP与UDP
- 在Ubuntu Desktop上开发classic snap应用
- 大数据交互平台Hue的优势
- 【Mybatis Generator】【配置详解】
- Oracle的DML语言必备基础知识
- 【转】使用Python matplotlib绘制股票走势图
- [leetcode]20. Valid Parentheses(java)
- (二)微信小程序之文件结构目录解析
- shell_umask用法