写在前面

上篇文章介绍了缓存的基本概念及用途,另外也举了一个简单的例子,数据缓存(将一些耗费时间的数据加入到一个对象缓存集合中,以键值的方式存储。可以通过使用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. 移动应用安全开发指南(Android)--数据验证

    概述 移动应用往往通过数据的发送.接收和处理来完成一系列功能,通常情况下,处理的数据绝大部分都来源于外部(比如网络.内部或外部存储和用户输入等),对这些数据处理不当会导致各种各样的漏洞和风险,比代码执 ...

  2. CentOS 6下搭建LAMP环境

    第一步,使用Xshell管理工具连接远程服务器 第二步,输入服务器账号密码登录远程服务器 如果centos内置的yum源可用的软件偏少或者版本过低,请更新! 首先备份/etc/yum.repos.d/ ...

  3. FPGA LVDS I/O as an Analog Programmable Comparator

    http://www.eetimes.com/author.asp?section_id=36&doc_id=1320289 Seeing the new ADC IP being bandi ...

  4. boost.python编译及演示样例

    欢迎转载,转载请注明原文地址:http://blog.csdn.net/majianfei1023/article/details/46781581 linux编译boost的链接:http://bl ...

  5. 使用cwrsync做服务器文件夹同步

    首先要下载cwRsync的服务端和客户端软件(4.05免费版),下载地址如下: https://www.itefix.no/i2/cwrsync 具体的配置过程和遇到的问题可参考: http://ww ...

  6. ODS与数据仓库

    数据仓库是目前主要的数据存储体系.数据仓库之增W.H.Inmon认为,数据仓库是指支持管理决策过程的.面向主题的.集成的.随时间而变的.持久的数据的集合.简单地说,一个数据仓库就一个自数据库的商业应用 ...

  7. MySQL Cluster(MySQL 集群) 初试

    MySQL Cluster 是MySQL适合于分布式计算环境的高实用.高冗余版本.它采用了NDB Cluster 存储引擎,允许在1个 Cluster 中运行多个MySQL服务器.在MyQL 5.0及 ...

  8. Kubernetes集群安全概述

    API的访问安全性 API Server的端口和地址 在默认情况下,API Server通过本地端口和安全端口两个不同的HTTP端口,对外提供API服务,其中本地端口是基于HTTP协议的,用于在本机( ...

  9. C++构造函数、析构函数、虚析构函数

    1.构造函数 C++中的构造函数是用于初始化类的各种变量以及分配资源等.主要的注意事项是: (1)在继承关系中先初始化父类对象后初始化子类对象. (2)在一个类中按照变量的声明顺序,对类中的变量进行初 ...

  10. Quartz学习笔记

    :30发送email通知客户最新的业务情况. java.util.Timer和java.util.TimerTask    Timer和TimerTask是能够完毕job schedule的两个jdk ...