ASP.NET中Cache缓存详解
一.缓存概述
(一)ASP.NET缓存技术种类
在ASP.NET实际项目开发中,我们可以采取基本的三种缓存技术:页面缓存、数据源缓存和数据缓存
1.页面缓存
给页面添加 <%@OutputCache Duration="15" VaryByParam="none"%> 标签就可以启用页面缓存,
页面中的ASP.NET代码,数据源在缓存期间都不会运行,而是直接输出缓存的页面内容,Duration 表示缓存时间,以秒为单位,超过这个时间则缓存失效,再次生成后会再缓存15秒,以些类推。
在ASP.NET中页面缓存的使用方法非常的简单,只需要在aspx页的顶部加这样一句声明即可:
<%@ OutputCache Duration="60" VaryByParam="none" %>
注意:Duration:缓存的时间(秒),这是必选属性。如果未包含该属性,将出现分析器错误。
VaryByParam:是指页面根据使用 POST 或 GET 发送的名称/值对(参数)来更新缓存的内容,多个参数用分号隔开。如果不希望根据任何参数来改变缓存内容,请将值设置为 none。如果希望通过所有的参数值改变都更新缓存,请将属性设置为星号 (*)。
例如: http://localhost:1165/16-4-3/WebForm1.aspx?p=1
则可以在WebForm1.aspx页面头部声明缓存:<%@ OutputCache Duration="60" VaryByParam="p" %>
以上代码设置页面缓存时间是60秒,并根据p参数的值来更新缓存,即p的值发生变化才更新缓存。
如果一直是WebForm1.aspx?p=1访问该页,则页面会缓存当前数据,当p=2时又会执行后台代码更新缓存内容。
如果有多个参数时,如:http://localhost:1165/16-4-3/WebForm1.aspx?p=1&n=1
可以这样声明:<%@ OutputCache Duration="60" VaryByParam="p;n" %>
前台代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="CacheWebApp._16_4_3.WebForm1" %>
<%@ OutputCache Duration="60" VaryByParam="none" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>页面缓存示例</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
后台代码
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Label1.Text = DateTime.Now.ToString();
}
}
2.数据源缓存
设定ObjectDataSource的CacheDuration (缓存时间:秒),EnableCaching=true
这样每隔CacheDuration指定的时间段才调用SelectMethod指定的方法来执行数据库查询,其他时候都是直接返回缓存的数据。
3.缓存其他 (自定义缓存)
页面缓存、数据源缓存等内部都是使用HttpRuntime.Cache来实现缓存的,在一些页面缓存、数据源
缓存完成不了的特殊的缓存要求中,可以直接调用HttpRuntime.Cache进行缓存。
二。缓存依赖
1.文件缓存依赖
这种策略让缓存依赖于一个指定的文件,通过改变文件的更新日期来清除缓存。
/// <summary>
/// 获取当前应用程序指定CacheKey的Cache对象值
/// </summary>
/// <param name="CacheKey">索引键值</param>
/// <returns>返回缓存对象</returns>
public static object GetCache(string CacheKey)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
return objCache[CacheKey];
}
/// <summary>
/// 设置以缓存依赖的方式缓存数据
/// </summary>
/// <param name="CacheKey">索引键值</param>
/// <param name="objObject">缓存对象</param>
/// <param name="cacheDepen">依赖对象</param>
public static void SetCache(string CacheKey, object objObject, System.Web.Caching.CacheDependency dep)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(
CacheKey,
objObject,
dep,
System.Web.Caching.Cache.NoAbsoluteExpiration, //从不过期
System.Web.Caching.Cache.NoSlidingExpiration, //禁用可调过期
System.Web.Caching.CacheItemPriority.Default,
null);
}
protected void Page_Load(object sender, EventArgs e)
{
string CacheKey = "cachetest";
object objModel = GetCache(CacheKey);//从缓存中获取
if (objModel == null) //缓存里没有
{
objModel = DateTime.Now;//把当前时间进行缓存
if (objModel != null)
{
//依赖 C:\\test.txt 文件的变化来更新缓存
System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency("C:\\test.txt");
SetCache(CacheKey, objModel, dep);//写入缓存
}
}
Label1.Text = objModel.ToString();
}
2.数据库缓存依赖
第一步: 修改web.config,让项目启用SqlCacheDependency 。
将下列代码加入web.config的<system.web>节:
<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings>
<add name="strcodematic" connectionString="data source=127.0.0.1;initial catalog=codematic;user id=sa;password=" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<caching>
<sqlCacheDependency enabled="true" pollTime="6000">
<databases>
<add name="codematic" connectionStringName="strcodematic" />
</databases>
</sqlCacheDependency>
</caching>
<compilation debug="true">
</compilation>
<authentication mode="Windows"/>
</system.web>
</configuration>
第二步:为 数据库启用缓存依赖,使用C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727中的aspnet_regsql.exe:
注册:aspnet_regsql -S . -E -ed -d 数据库名 -et -t 版本表名
第三步:在代码中使用缓存,并为其设置SqlCacheDependency依赖:
/// <summary>
/// 获取当前应用程序指定CacheKey的Cache对象值
/// </summary>
/// <param name="CacheKey">索引键值</param>
/// <returns>返回缓存对象</returns>
public static object GetCache(string CacheKey)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
return objCache[CacheKey];
}
/// <summary>
/// 设置以缓存依赖的方式缓存数据
/// </summary>
/// <param name="CacheKey">索引键值</param>
/// <param name="objObject">缓存对象</param>
/// <param name="cacheDepen">依赖对象</param>
public static void SetCache(string CacheKey, object objObject, System.Web.Caching.CacheDependency dep)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(
CacheKey,
objObject,
dep,
System.Web.Caching.Cache.NoAbsoluteExpiration,//从不过期
System.Web.Caching.Cache.NoSlidingExpiration,//禁用可调过期
System.Web.Caching.CacheItemPriority.Default,
null);
}
protected void Page_Load(object sender, EventArgs e)
{
string CacheKey = "cachetest";
object objModel = GetCache(CacheKey);//从缓存中获取
if (objModel == null)//缓存里没有
{
objModel = GetData();//把当前时间进行缓存
if (objModel != null)
{
//依赖数据库codematic中的P_Product表变化 来更新缓存
System.Web.Caching.SqlCacheDependency dep = new System.Web.Caching.SqlCacheDependency("codematic", "P_Product");
SetCache(CacheKey, objModel, dep);//写入缓存
}
}
GridView1.DataSource = (DataSet)objModel;
GridView1.DataBind();
}
//查询数据
private DataSet GetData()
{
string conString = "data source=127.0.0.1;initial catalog=codematic;user id=sa;password=";
string strSQL = "SELECT * FROM P_Product";
SqlConnection myConnection = new SqlConnection(conString);
DataSet ds = new DataSet();
myConnection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(strSQL, myConnection);
adapter.Fill(ds, "Product");
myConnection.Close();
return ds;
}
注意:SqlCacheDependency(string databaseEntryName,string tableName)
databaseEntryName :是在Web.config 文件的 caching 节的 sqlCacheDependency 的 databases 元素中定义的数据库的名称。
tableName :与 SqlCacheDependency 关联的数据库表的名称。
缓存依赖具体可参考:https://kb.cnblogs.com/page/69727/
ASP.NET中缓存使用介绍参考:https://www.cnblogs.com/xdot/p/5860205.html