写在前面

上篇文章介绍了缓存的基本概念及用途,另外也举了一个简单的例子,数据缓存(将一些耗费时间的数据加入到一个对象缓存集合中,以键值的方式存储。可以通过使用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(), 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 = ,
//
// 摘要:
// The item is removed from the cache because it expired.
Expired = ,
//
// 摘要:
// The item is removed from the cache because the system removed it to free memory.
Underused = ,
//
// 摘要:
// The item is removed from the cache because the cache dependency associated with
// it changed.
DependencyChanged =
}

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

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

[Asp.net]缓存之页面缓存,控件缓存,缓存依赖的更多相关文章

  1. 如何清除应用程序承载 WebBrowser 控件时缓存

    原文:如何清除应用程序承载 WebBrowser 控件时缓存 http://support.microsoft.com/kb/262110/zh-cn察看本文应用于的产品 function loadT ...

  2. ASP.NET MVC 中使用用户控件——转

    讲讲怎么在 ASP.NET MVC2中使用用户控件.首先我们新建一个用户控件,   我们命名为SelectGroup.ascx,代码如下 <%@ Control Language="C ...

  3. ASP.NET的面包屑导航控件、树形导航控件、菜单控件

    原文:http://blog.csdn.net/pan_junbiao/article/details/8579293 ASP.NET的面包屑导航控件.树形导航控件.菜单控件. 1. 面包屑导航控件— ...

  4. asp.net 弹出式日历控件 选择日期 Calendar控件

    原文地址:asp.net 弹出式日历控件 选择日期 Calendar控件 作者:逸苡 html代码: <%@ Page Language="C#" CodeFile=&quo ...

  5. Xamarin自定义布局系列——PivotPage,多页面切换控件

    PivotPage ---- 多页面切换控件 PivotPage是一个多页面切换控件,类似安卓中的ViewPager和UWP中的Pivot枢轴控件. 起初打算直接通过ScrollView+StackL ...

  6. js-关于iframe:从子页面给父页面的控件赋值方法

    项目中我们经会用到iframe,可能还会把iframe里的数值赋值给父页面空间. 接下来我们来说说有关于iframe赋值给父页面的方法. 1.子页面iframe给父页面的控件赋值方法. parent. ...

  7. findControl 可以获取前台页面的控件

    findControl 可以获取前台页面的控件

  8. cesium页面小控件的隐藏

    cesium页面小控件的隐藏 1   创建一个Viewer var viewer = new Cesium.Viewer('cesiumContainer');//cesiumContainer为di ...

  9. C#代码总结02---使用泛型来获取Asp前台页面全部控件,并进行属性修改

    该方法:主要用于对前台页面的不同类型(TextBox.DropDownList.等)或全部控件进行批量操作,用于批量修改其属性(如,Text.Enable). private void GetCont ...

  10. amazeUI的confirm控件记录缓存问题的解决办法

    场景:列表行每行都有删除按钮,点击删除按钮将行记录的id传给js方法,js方法中调用amazeui的confirm控件,确认删除function通过ajax执行删除行为. 问题现象:每次删除列表第一行 ...

随机推荐

  1. CentOS 6.9/7通过yum安装指定版本的JDK/Maven

    说明:通过yum好处其实很多,环境变量不用配置,配置文件放在大家都熟悉的地方,通过rpm -ql xxx可以知道全部文件的地方等等. 一.安装JDK(Oracle JDK 1.8) # wget -- ...

  2. GridView Item 大小可能不一样,如何保持同一行的Item 高度大小相同,且GridView高度自适应!

    昨天用到GridView,但是遇到几个问题,就是GridView默认的item其实大小是一致的,但是我们经常会遇到item大小不同,系统默认会留白的问题,很头疼!如下图这样的:      就会造成,右 ...

  3. 强悍的javascript手势库

    /** * Toucher * git:https://github.com/cometwo/Toucher-1 */ "use strict"; (function (root, ...

  4. Static Nested Class 和 Inner Class的不同?

    Nested Class (一般是C++的说法),Inner Class (一般是JAVA的说法).Java内部类与C++嵌套类最大的不同就在于是否有指向外部的引用上. 注: 静态内部类(Inner ...

  5. poj 3130 How I Mathematician Wonder What You Are! - 求多边形有没有核 - 模版

    /* poj 3130 How I Mathematician Wonder What You Are! - 求多边形有没有核 */ #include <stdio.h> #include ...

  6. 神经网络可以拟合任意函数的视觉证明A visual proof that neural nets can compute any function

    One of the most striking facts about neural networks is that they can compute any function at all. T ...

  7. Python学习(九)IO 编程 —— 文件夹及文件操作

    Python 文件夹及文件操作 我们经常会与文件和目录打交道,对于这些操作,python可以使用 os 及 shutill 模块,其中包含了很多操作文件和目录的函数. os 可以执行简单的文件夹及文件 ...

  8. 通过javascript获取元素position

    function getOffset( el ) { var _x = 0; var _y = 0; while( el && !isNaN( el.offsetLeft ) & ...

  9. Gerrit代码审核服务器搭建全过程

    Gerrit代码审核服务器搭建全过程 转载请标明出处:http://blog.csdn.net/ganshuyu/article/details/8978614 环境:Ubuntu12.xx 1.建立 ...

  10. Java import javax.servlet 出错

    Error: The import javax.servlet cannot be resolved The import javax.servlet.http.HttpServletRequest ...