VictorStone

导航

 

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();
    }

 

posted on 2015-02-05 13:04  VictorStone  阅读(230)  评论(0编辑  收藏  举报