Caching

http://www.cnblogs.com/kissdodog/archive/2013/05/07/3064895.html

第三方开源代码,但是没有过期释放缓存和依赖。

    public interface IMemory<P, R>
    {
        bool HasResultFor(P val);
        R ResultFor(P val);
        void Remember(P val, R result);
    }

    public class Memory<P, R> : IMemory<P, R>
    {
        Dictionary<P, R> storage = new Dictionary<P, R>();

        public bool HasResultFor(P val)
        {
            return storage.ContainsKey(val);
        }

        public R ResultFor(P val)
        {
            return storage[val];
        }

        public void Remember(P val, R result)
        {
            storage[val] = result;
        }
    }

    public static class Memoizer<P, R>
    {
        static object memoryListLock = new object();
        static Dictionary<string, IMemory<P, R>> memories;
        static Dictionary<string, IMemory<P, R>> Memories
        {
            get
            {
                lock (memoryListLock)
                {
                    if (memories == null)
                        memories = new Dictionary<string, IMemory<P, R>>();
                    return memories;
                }
            }
        }
        private static T CreateMemory<T>(string key) where T : IMemory<P, R>, new()
        {
            T memory = new T();
            memories[key] = memory;
            return memory;
        }
        public static IMemory<P, R> CreateMemory(string key)
        {
            lock (memoryListLock)
            {
                if (Memories.ContainsKey(key)) return memories[key];
                return  CreateMemory<Memory<P,R>>(key);    
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="key">对象的全名</param>
        /// <returns></returns>
        public static IMemory<P, R> GetMemory(string key)
        {
            if (!(Memories.ContainsKey(key)))
                return CreateMemory(key);
            return Memories[key];
        }
    }
View Code
            var memory = Memoizer<int, int>.GetMemory("ConsoleApplication1.Program");
            if (!memory.HasResultFor(key))
            {
                Console.WriteLine("未包含" + key);
                memory.Remember(key, key);
            }
View Code

Cache:但是报错:

static NameValueCollection nvc = new NameValueCollection();
        static void Main(string[] args)
        {
            Thread t = new Thread(ThreadTest);
            t.IsBackground = true;
            t.Start();
            t.Join();
            Thread t1 = new Thread(ThreadTest);
            t1.IsBackground = true;
            t1.Start();
            t1.Join();
            Console.Read();
        }

        static void ThreadTest()
        {
            for (int i = 0; i < 100; i++)
            {
                ConsoleDate(i);
            }
        }

        public static void ConsoleDate(int key)
        {
            DataClass<int> dc = CacheMemory<DataClass<int>>.GetCache(key.ToString());
            if (dc == null)
            {
                Console.WriteLine("未包含" + key);
                dc = new DataClass<int>(key);
                CacheMemory<DataClass<int>>.SetCache(key.ToString(), dc, DateTime.MaxValue, TimeSpan.FromMilliseconds(1));
            }
            CacheMemory<DataClass<int>>.GetCache(key.ToString()).ConsoleData();
        }

        public class DataClass<T> where  T : struct
        {
            private T _T;
            public DataClass(T t)
            {
                _T = t;
            }

            public T ConsoleData()
            {
                return _T;
            }
        }
View Code

可以把CacheMemory<DataClass<int>>.GetCache(key.ToString()).ConsoleData();改成dc.ConsoleData();

因为在GetCache时,可能这个key已经过期被移除了。

 

   public static class CacheMemory<T> where T : class
    {
        // 考虑到杭州经常会使用政策库算法,然而方案比例和截单日可能会有变动,故将滑动时间改成绝对时间,而配置的SlidingExpirationHour则不修改
        private static double _absoluteExpiration = double.Parse(ConfigurationManager.AppSettings["SlidingExpirationHour"]);
        //public static double AbsoluteExpiration
        //{
        //    get
        //    {
        //        return _absoluteExpiration;
        //    }
        //    set
        //    {
        //        _absoluteExpiration = value;
        //    }
        //}

        //<summary>
        ///获取当前应用程序指定CacheKey的Cache对象值
        ///</summary>
        ///<param name="CacheKey">索引键值</param>
        ///<returns>返回缓存对象</returns>
        public static T GetCache(string CacheKey)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            return objCache[CacheKey] as T;
        }

        ///<summary>
        ///设置当前应用程序指定CacheKey的Cache对象值
        ///</summary>
        ///<param name="CacheKey">索引键值</param>
        ///<param name="objObject">缓存对象</param>
        public static void SetCache(string CacheKey, T objObject)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject, null, DateTime.Now.AddHours(_absoluteExpiration), System.Web.Caching.Cache.NoSlidingExpiration);
        }

        ///<summary>
        ///设置当前应用程序指定CacheKey的Cache对象值
        ///</summary>
        ///<param name="CacheKey">索引键值</param>
        ///<param name="objObject">缓存对象</param>
        ///<param name="absoluteExpiration">绝对过期时间</param>
        ///<param name="slidingExpiration">最后一次访问所插入对象时与该对象过期时之间的时间间隔</param>
        public static void SetCache(string CacheKey, T objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);
        }
    }
View Code

利用Cache

posted @ 2016-12-06 17:40  江境纣州  阅读(42)  评论(0)    收藏  举报