[Asp.net]缓存之页面缓存,控件缓存,缓存依赖

写在前面

上篇文章介绍了缓存的基本概念及用途,另外也举了一个简单的例子,数据缓存(将一些耗费时间的数据加入到一个对象缓存集合中,以键值的方式存储。可以通过使用Cache.Insert()方法来设置缓存的过期,优先级,依赖项等)。本片文章将介绍一下页面缓存,控件缓存,缓存依赖方面的内容,希望对你有所帮助。

系列文章

[Asp.net]缓存简介

页面缓存

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="pageCache.aspx.cs" Inherits="Wolfy.AngularJs.pageCache" %>

<!--Duration:缓存5秒,VaryByParam:缓存不带参数的本页面-->
<%@ OutputCache Duration="5" VaryByParam="none" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        </div>
    </form>
</body>
</html>
    public partial class pageCache : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Response.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            }
        }
    }

在页面上指令<%@ OutputCache Duration="5" VaryByParam="none" %> Duration:设置缓存过期时间,这里设置为5,则5秒内访问该页面都是从缓存中读取数据,5秒过期后,则再次走PageLoad方法。VaryByParam:指定页面参数,比如:有这样一个url:http://localhost:18174/pageCache.aspx?id=1&name=wolfy,它的参数就是id和name,那么我们就可以在指令中这样来写:<%@ OutputCache Duration="5" VaryByParam="id;name" %> ,多个参数以分号分开,这样的好处就是我们可以为每个页面都进行设置缓存。当然,我们可以使用下面的指令进行缓存所有的页面,<%@ OutputCache Duration="5" VaryByParam="*" %> 

控件缓存

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="controlcache.aspx.cs" Inherits="Wolfy.AngularJs.controlcache" %>

<%@ OutputCache Duration="5" VaryByControl="lblCache" %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label Text="" ID="lblCache" runat="server" />
        </div>
    </form>
</body>
</html>
    public partial class controlcache : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.lblCache.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }
        }
    }

 <%@ OutputCache Duration="5" VaryByControl="lblCache" %> Duration:指定缓存过期时间,VaryByControl指定缓存的控件(控件id)。

缓存依赖

缓存依赖,顾名思义就是依赖于其他资源,若资源改变了,则缓存也将过期。

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                object obj = Cache.Get("file");
                if (obj == null)
                {
                    string strCache = string.Empty;
                    string filePath = Server.MapPath("cache.txt");
                    strCache = File.ReadAllText(filePath);
                    //缓存依赖
                    CacheDependency cacheDependency = new CacheDependency(filePath);
                    //如果*.txt这个文件的内容不变就一直读取缓存中的数据,
                    //一旦文件中的数据改变里面重新读取 *.txt文件中的数据
                    Cache.Insert("file", strCache, cacheDependency);
                    Response.Write(strCache);
                }
                else
                {
                    Response.Write(Cache["file"].ToString());
                }
            }
        }

比如文件cache.txt内容为:2015-08-16 10:23:46,如果改变该值,则下次加载的时候会重新读取,否则直接输出缓存内容。

如果,我们想在缓存过期的时候,记录一下日志,该怎么做?当然,Cache的Insert方法也提供了这样的回掉函数。

    public partial class cachedependency : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                object obj = Cache.Get("file");
                if (obj == null)
                {
                    string strCache = string.Empty;
                    string filePath = Server.MapPath("cache.txt");
                    strCache = File.ReadAllText(filePath);
                    //缓存依赖
                    CacheDependency cacheDependency = new CacheDependency(filePath);
                    //如果*.txt这个文件的内容不变就一直读取缓存中的数据,
                    //一旦文件中的数据改变里面重新读取 *.txt文件中的数据
                    Cache.Insert("file", strCache, cacheDependency, DateTime.Now.AddSeconds(5), Cache.NoSlidingExpiration, CacheItemPriority.Low, OnCacheItemUpdaeCallback);
                    Response.Write(strCache);
                }
                else
                {
                    Response.Write(Cache["file"].ToString());
                }
            }
        }
        private void OnCacheItemUpdaeCallback(string key, object value, CacheItemRemovedReason reason)
        {
            File.WriteAllText(Server.MapPath("log.txt"), reason.ToString());
        }
    }

CacheItemRemoveReason枚举有以下的值:

    //
    // 摘要:
    //     Specifies the reason an item was removed from the System.Web.Caching.Cache.
    public enum CacheItemRemovedReason
    {
        //
        // 摘要:
        //     The item is removed from the cache by a System.Web.Caching.Cache.Remove(System.String)
        //     method call or by an System.Web.Caching.Cache.Insert(System.String,System.Object)
        //     method call that specified the same key.
        Removed = 1,
        //
        // 摘要:
        //     The item is removed from the cache because it expired.
        Expired = 2,
        //
        // 摘要:
        //     The item is removed from the cache because the system removed it to free memory.
        Underused = 3,
        //
        // 摘要:
        //     The item is removed from the cache because the cache dependency associated with
        //     it changed.
        DependencyChanged = 4
    }

 上面几个枚举值,说明了移除缓存的原因。

web.config设置缓存

1.配置文件中指定缓存参数,在页面只需指定CacheProfile即可。

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="pageIndexCacheProfile" duration="20"/>
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>
  </system.web>
</configuration>

注意,在页面中也需要指定pageIndexCacheProfile,名字需要相同。

<%@ OutputCache  CacheProfile="pageIndexCacheProfile" VaryByParam="none" %>

 2.减少缓存时间

  <system.webServer>
    <caching>
      <profiles>
        <remove extension=".aspx" />
        <add extension=".aspx" policy="CacheForTimePeriod"
        kernelCachePolicy="DontCache" duration="00:00:01" varyByQueryString="*" />
      </profiles>
    </caching>
  </system.webServer>

 3.关闭某个页面的caching功能

  <location path="CacheIndex.aspx">
    <system.webServer>
      <caching>
        <profiles>
          <remove extension=".aspx" />
          <add extension=".aspx" policy="DontCache" kernelCachePolicy="DontCache"/>
        </profiles>
      </caching>
    </system.webServer>
  </location>

4.关闭所有页面的缓存

  <system.webServer>
    <caching>
      <profiles>
        <remove extension=".aspx" />
        <add extension=".aspx" policy="DontCache" kernelCachePolicy="DontCache"/>
      </profiles>
    </caching>
  </system.webServer>

5.关闭某个目录下的页面的缓存

  <location path="~/Admin,~/Product">
    <system.webServer>
      <caching>
        <profiles>
          <remove extension=".aspx" />
          <add extension=".aspx" policy="DontCache" kernelCachePolicy="DontCache"/>
        </profiles>
      </caching>
    </system.webServer>
  </location>

 总结

缓存的基本内容及应用就到这里了,之后会学习下redis的相关内容。

参考文章

http://www.cnblogs.com/knowledgesea/archive/2012/06/20/2536603.html

posted @ 2015-08-18 19:50  wolfy  阅读(1147)  评论(1编辑  收藏  举报