zoukankan      html  css  js  c++  java
  • 通过委托让缓存操作更优雅

    string key = sysVar.CacheKey.CurrentUser;

    var CurrentUser = _cacheManager.Get(key, ()=>{ ctx.GetCurrentUser();});

    缓存操作接口的扩展方法:

        public static class CacheExtensions
        {
            /// <summary>
            /// 从缓存中取指定key的内容,不存在则以匿名方法写入
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="cacheManager"></param>
            /// <param name="key"></param>
            /// <param name="acquire"></param>
            /// <returns></returns>
            public static T Get<T>(this ICacheManager cacheManager, string key, Func<T> acquire)
            {
                return Get(cacheManager, key, 60, acquire);
            }
    
            /// <summary>
            /// 如果有对应key,则添加缓存(以匿名方法写入)。
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="cacheManager"></param>
            /// <param name="key"></param>
            /// <param name="cacheTime">缓存时间</param>
            /// <param name="acquire"></param>
            /// <returns></returns>
            public static T Get<T>(this ICacheManager cacheManager, string key, int cacheTime, Func<T> acquire)
            {
                if (cacheManager.IsSet(key)) //如果已经有缓存
                {
                    return cacheManager.Get<T>(key); //直接从缓存返回
                }
                else
                {
                    var result = acquire(); //获得委托中的结果
                    //if (result != null)
                    cacheManager.Set(key, result, cacheTime); //写入缓存
                    return result;          //然后缓存
                }
            }
        }

     _cacheManager.Get(key, () => { ......; return result; }

        public interface ICacheManager
        {
            T Get<T>(string key);
            void Set(string key, object data, int cacheTime);
    
            /// <summary>
            /// 是否已经缓存
            /// </summary>
            bool IsSet(string key);
            void Remove(string key);
            void RemoveByPattern(string pattern);
            void Clear();
        }
  • 相关阅读:
    CH the luckiest number 欧拉函数 同余
    bzoj1257余数求和 数论分块 暴力
    luogup1463 反素数
    CH3101 阶乘分解
    T10396 曹老板斗地主(中度模拟)
    NOIP 2015子串(DP)
    CF1205B Shortest Cycle(Floyd判最小环)
    P2055 [ZJOI2009]假期的宿舍(二分图匹配)
    灾后重建(最短路)
    CF1098A Sum in the tree(贪心)
  • 原文地址:https://www.cnblogs.com/shi5588/p/4274548.html
Copyright © 2011-2022 走看看