网站优化之缓存--页面缓存

网站优化之缓存--页面缓存

1. 缓存的基本定义:使用如下,注意该缓存只能在web下使用。

引入:using System.Web.Caching;命名空间
增加缓存添加方法:
/// <summary>
        /// 
        /// </summary>
        /// <param name="key">缓存key,全局唯一</param>
        /// <param name="value">缓存值</param>
        /// <param name="minutes">缓存时间(分钟)</param>
        /// <param name="useAbsoluteExpiration">是否绝对过期</param>
        public static void Add(string key, object value, int minutes, bool useAbsoluteExpiration)
        {
            if (key != null && value != null)
            {
                if (useAbsoluteExpiration)
                {
                    HttpContext.Current.Cache.Insert(key, value, null, DateTime.Now.AddMinutes(minutes), Cache.NoSlidingExpiration);
                }
                else
                {
                    HttpContext.Current.Cache.Insert(key, value, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, minutes, 0));
                }
            }
        }
增加移除缓存的方法:
public static object Remove(string key)
        {
            return HttpContext.Current.Cache.Remove(key);
        }
增加移除全部缓存的方法:
public static void RemoveAll()
        {
            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
            System.Collections.IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
            if (CacheEnum == null) return;
            while (CacheEnum.MoveNext())
            {
                Remove(CacheEnum.Key.ToString());
            }
        }
在使用缓存的地方,直接调用以上方法即可。

 

 

1. 页面缓存介绍:该缓存指的是对页面进行缓存,该事件在请求管道中第6个事件的时候就已经被定义。

2. asp.net mvc中页面缓存的基本使用:

 

 

[OutputCache(Duration = 100,VaryByParam ="*")]
        public ActionResult Index()
        {
            return View();
        }

3. 如上代码,页面缓存只需要在页面代码顶部中加入,就能够实现对页面的缓存。

[OutputCache(Duration = 100,VaryByParam ="*")]
参数介绍:
Duration :指的是过期事件,是按秒去计算。
VaryByParam:指的是请求的参数,如果两次请求的参数一致,并且对应的值一致,那么该请求的缓存就是一致,否则就不进行缓存。

posted @ 2020-09-30 23:28  锦大大的博客呀!  阅读(565)  评论(0编辑  收藏  举报