码迷,mamicode.com
首页 > Web开发 > 详细

ASP.NET-【缓存】-使用ASP.NET缓存

时间:2015-01-31 11:58:35      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:

缓存一个List 泛型结构

1.显示
            var s = Get("personsl");
            foreach (var item in s)
            {
                Response.Write(item.Name);
            }

2.获得数据

        //获得数据
        public List<Personal> Get(string key)
        {
            List<Personal> list = DTcms.Common.CacheHelper.Get<List<Personal>>(key);
            if (list == null || list.Count == 0)
            {
                DTcms.Common.CacheHelper.Insert("personsl", Create(), 30);
                list = DTcms.Common.CacheHelper.Get<List<Personal>>(key);
            }
            return list;
        }

3.创建数据源

        //创建数据源
        public List<Personal> Create()
        {
            List<Personal> list = new List<Personal>();
            for (int i = 0; i < 10; i++)
            {
                Personal p = new Personal(i.ToString(), "xiaoming" + i);
                list.Add(p);
            }
            return list;
        }
    //数据对象
    public class Personal
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public Personal(string id, string name)
        {
            this.ID = id;
            this.Name = name;
        }
    }

4.查看缓存个数

//异常不能示例话的
Response.Write(new System.Web.Caching.Cache().Count);
Response.Write(HttpRuntime.Cache.Count);

5.Cache 的绝对到期与滑动到期
绝对到期:设置绝对过期时间 到了指定时间以后会失效。(类似Cookie机制)
相对到期也称滑动到期:设置相对过期时间 指定时间内无访问会失效。(类似Session机制)

HttpRuntime.Cache与HttpContext.Current.Cache 为同一个对象
HttpRuntime.Cache.Add 存在相同的键会异常,返回缓存成功的对象 HttpRuntime.Cache.Insert存在相同的键会替换无返回值

HttpRuntime.Cache["key"] 使用字典的方式也可以读取和设置
HttpRuntime.Cache.Insert(key, value, null, DateTime.Now.AddSeconds(seconds), TimeSpan.Zero); //设置绝对过期时间 到了指定时间以后会失效 ps: TimeSpan.Zero == System.Web.Caching.Cache.NoSlidingExpiration
HttpRuntime.Cache.Insert(key, value, null, DateTime.MaxValue, TimeSpan.FromSeconds(seconds)); //设置相对过期时间 指定时间内无访问会失效 ps: DateTime.MaxValue == System.Web.Caching.Cache.NoAbsoluteExpiration

ASP.NET-【缓存】-使用ASP.NET缓存

标签:

原文地址:http://www.cnblogs.com/Sky-cloudless/p/4263783.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!