CacheHelper

时间:2022-02-21 18:16:35
public static ObjectCache Cache
        {
            get
            {
                return MemoryCache.Default;
            }
        }

        public static bool TryGetCache<T>(string key, ref T value)
        {
            object v = null;
            //Type t = typeof(T);
            bool hit;
            hit = TryGetCacheObject(key, ref v);
            if (hit)
                value = (T)v;
            return hit;
        }

        public static bool TryGetCacheStruct<T>(string key, ref T value) where T : struct
        {
            object v = null;
            bool hit = TryGetCacheObject(key, ref v);
            if (hit)
                value = (T)v;
            return hit;
        }

        public static bool TryGetCacheObject(string key, ref object value)
        {
            object v = Cache.Get(key);
            bool hit = false;
            if (v == null)
                hit = false;
            else if (v == DBNull.Value)
            {
                hit = true;
                value = null;
            }
            else
            {
                hit = true;
                value = v;
            }
            TraceHelper.Trace("Cache", string.Format("TryGetCache({0}) = {1}", key, hit));
            return hit;
        }

        public static bool ContainsCache(string key)
        {
            return Cache.Contains(key);
        }

        public static object GetCache(string key)
        {
            return Cache.Get(key);
        }

        public static void SetCache(string key, object value)
        {
            Cache.Set(key, value, CacheItemPolicy);
        }

        public static void SetCache(string key, object value, CacheItemPolicy cacheItemPolicy)
        {
            Cache.Set(key, value, cacheItemPolicy);
        }

        public static CacheItemPolicy CacheItemPolicy
        {
            get
            {
                CacheItemPolicy policy = new CacheItemPolicy();
                policy.SlidingExpiration = , AppConfiguration.CacheSlidingExpirationInMins, );
                return policy;
            }
        }

        public static void ClearCacheByPrefix(string prefix)
        {
            List<string> keys = new List<string>();
            foreach (var c in Cache)
            {
                if (c.Key.StartsWith(prefix))
                {
                    keys.Add(c.Key);
                }
            }
            foreach (var key in keys)
            {
                Cache.Remove(key);
            }
        }

Use:

string cachekey = string.Format("HasPermission_{0}_{1}", User.Id, functionName);
            bool result = false;
            if (!WebHelper.TryGetCache(cachekey, ref result))
            {
                result = roleBO.FunctionIsAllowForStaff(functionName, this.CurrentActualUser.Id);
                WebHelper.SetCache(cachekey, result);
            }