• 通过委托让缓存操作更优雅


    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();
        }
  • 相关阅读:
    根据方法名执行方法的例子
    修改cmd的默认路径
    事件处理程序的处理顺序问题
    类型事件定义
    修改应用程序搜索程序集的私有路径
    What's New in Visual Studio 2010
    IE 8 中选项卡通过颜色分组
    再谈CLR:无法避免的装箱
    环境变量(Environment Variable)那点事
    默认情况下程序启动后到底是几个线程?
  • 原文地址:https://www.cnblogs.com/shi5588/p/4274548.html
Copyright © 2020-2023  润新知