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

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

    }

 

你可能感兴趣的:(缓存)