zoukankan      html  css  js  c++  java
  • 基于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         }

      

  • 相关阅读:
    JavaScript数据结构和算法----队列
    JavaScript数据结构和算法----栈
    ES6箭头函数
    JavaScript的错误处理
    easing--缓动函数--贝塞尔函数--圆盘转动抽奖应用
    node之子线程child_process模块
    node上传文件并在网页中展示
    Python内置函数之int()
    从Python的角度来看编码与解码
    关于.pyc文件
  • 原文地址:https://www.cnblogs.com/NoRoad/p/6256046.html
Copyright © 2011-2022 走看看