基于MemoryCache的缓存辅助类

背景:

  1. 什么是MemoryCache?

    memoryCache就是用电脑内存做缓存处理

  2.使用范围?

    可用于不常变的数据,进行保存在内存中,提高处理效率

代码:

 1         /// <summary>
 2         /// 基于MemoryCache的缓存辅助类
 3         /// </summary>
 4         public static class MemoryCacheHelper
 5         {
 6             private static readonly Object _locker = new object();
 7 
 8             public static T GetCacheItem<T>(String key, Func<T> cachePopulate, TimeSpan? slidingExpiration = null, DateTime? absoluteExpiration = null)
 9             {
10                 if (String.IsNullOrWhiteSpace(key)) throw new ArgumentException("Invalid cache key");
11                 if (cachePopulate == null) throw new ArgumentNullException("cachePopulate");
12                 if (slidingExpiration == null && absoluteExpiration == null) throw new ArgumentException("Either a sliding expiration or absolute must be provided");
13 
14                 if (MemoryCache.Default[key] == null)
15                 {
16                     lock (_locker)
17                     {
18                         if (MemoryCache.Default[key] == null)
19                         {
20                             var item = new CacheItem(key, cachePopulate());
21                             var policy = CreatePolicy(slidingExpiration, absoluteExpiration);
22 
23                             MemoryCache.Default.Add(item, policy);
24                         }
25                     }
26                 }
27 
28                 return (T)MemoryCache.Default[key];
29             }
30 
31             private static CacheItemPolicy CreatePolicy(TimeSpan? slidingExpiration, DateTime? absoluteExpiration)
32             {
33                 var policy = new CacheItemPolicy();
34 
35                 if (absoluteExpiration.HasValue)
36                 {
37                     policy.AbsoluteExpiration = absoluteExpiration.Value;
38                 }
39                 else if (slidingExpiration.HasValue)
40                 {
41                     policy.SlidingExpiration = slidingExpiration.Value;
42                 }
43 
44                 policy.Priority = CacheItemPriority.Default;
45 
46                 return policy;
47             }
48         }

 

  

posted @ 2017-01-06 13:50  NoRoadZH  阅读(1077)  评论(1编辑  收藏  举报