当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET Cache的一些总结分享

ASP.NET Cache的一些总结分享

2017年12月12日  | 移动技术网IT编程  | 我要评论

冯静老公,cctv3在线直播,李胜基资料

1.1.1 摘要
最近我们的系统面临着严峻性能瓶颈问题,这是由于访问量增加,客户端在同一时间请求增加,这迫使我们要从两个方面解决这一问题,增加硬件和提高系统的性能。

大家可以通过各种各样的方法去优化我们系统,本篇博文将介绍通过cache方法来优化系统的性能,减轻系统的负担。

1.1.2 正文

不同位置的缓存

在web应用程序中的使用缓存位置主要有:客户端浏览器缓存、客户端和服务器中以及服务器端,因此缓存可以分为以下几类:

客户端缓存(client caching)
代理缓存(proxy caching)
反向代理缓存(reverse proxy caching)
服务器缓存(web server caching)
asp.net中的缓存
asp.net中有两种缓存类型:输出缓存和数据缓存。

输出缓存:这是最简单的缓存类型,它保存发送到客户端的页面副本,当下一个客户端发送相同的页面请求时,此页面不会重新生成(在缓存有限期内),而是从缓存中获取该页面;当然由于缓存过期或被回收,这时页面会重新生成。

数据缓存

除此之外,还有两个特殊的缓存:片段缓存和数据源缓存。

片段缓存:这是一种特殊的输出缓存,它不是缓存整个页面,而是缓存部分页面;由于缓存整个页面通常并不可行,因为页面的某些部分是针对用户定制的(例如用户登陆信息),但我们可以把应用程序中共享的部分进行缓存,这时我们可以考虑使用片段缓存和用户控件缓存。

数据源缓存:是建立在数据源控件的缓存,它包括sqldatasource、objectdatasource和xmldatasource控件。数据源缓存使用数据缓存方式,不同的是我们不需要通过显示方法处理缓存;我们只需设置相应的属性,然后数据源控件就能存储和检索数据。

输出缓存
输出缓存可以把最终呈现的页面缓存起来,当客户端再次请求同一页面时,控制对象不再重新创建,页面的生命周期不再启动,无需再次执行代码,通过在缓存中获取缓存的页面。

现在我们设计一个页面,每当用户发送页面请求时,就获取当前代码执行的时间,然后显示在页面上。



图1输出缓存

这是再简单不过的例子,每当用户发送页面请求都会更新页面显示的时间,这是由于每次请求都获取了一个新的页面,实际情况中,我们并不需要实时的响应用户每个页面请求,我们可以通过输出缓存把页面缓存起来每当用户发送同一页面请求时,而且在缓存有效期间,可以通过输出缓存把缓存的页面返回给用户。

我们要实现输出缓存,只需在页面中添加如下代码:
复制代码 代码如下:

<!-- adds outputcache directive -->
<%@ outputcache duration="23" varybyparam="none" %>

它支持五个属性,其中两个属性duration和varybyparam是必填的

duration

必需属性。页面应该被缓存的时间,以秒为单位。必须是正整数。

location

指定应该对输出进行缓存的位置。如果要指定该参数,则必须是下列选项之一:any、client、downstream、none、server 或 serverandclient。

varybyparam

必需属性。request 中变量的名称,这些变量名应该产生单独的缓存条目。"none" 表示没有变动。"*" 可用于为每个不同的变量数组创建新的缓存条目。变量之间用 ";" 进行分隔。

varybyheader

基于指定的标头中的变动改变缓存条目。

varybycustom

允许在 global.asax 中指定自定义变动(例如,"browser")。

表1输出缓存属性

这里我们把输出缓存的有效期设置为23秒,也就是说,当缓存超过有效期就会被回收;当用户再次请求该页面时,就要重新创建页面。

客户端缓存
另一种选择是客户端缓存,如果用户在浏览器中点击“后退”按钮或在地址栏中重新输入url,那么在这种情况下,浏览器将从缓存获取页面;然而,如果用户点击“刷新”按钮,那么浏览器中缓存将失效,浏览器发送页面请求。

如果我们要使用客户端缓存,只需指定outputcache中的属性location=”client”就ok了,具体代码如下所示:

复制代码 代码如下:

<!-- sets client outputcache -->
<%@ outputcache duration="23" varybyparam="none" location="client" %>


通过在outputcache中添加location属性,我们实现了客户端缓存,通过设置客户端缓存我们能够减少的客户端请求,也许有人会问:“每个用户第一次页面请求都需要服务器来完成,这不能很好的减少服务的压力”。的确是这样,相对于服务器缓存,客户端缓存并没有减少代码的执行和数据库的操作,但是当我们把包含个性化数据的页面缓存在服务器中,客户端请求页面时,由于不同的用户个性化数据不同,这将会导致请求出现错误,所以我们可以使用片段缓存把公用的部分缓存起来或客户端缓存把用户信息缓存起来。

query string缓存
在前面的例子中,我们把outputcache中的varybyparam属性设置为none,那么asp.net程序只缓存一个页面副本;如果页面请求包含查询参数,那么在缓存的有效期内,我们只可以查看到只是缓存结果,假设我们有个报表程序,它提供用户根据产品名称查询相关的产品信息。

首先我们创建两个页面:查询和结果页面,由于时间关系我们已经把页面设计好了,具体如下所示:

cahce1

cache2

图2报表程序

首先我们提供查询页面,让用户根据成品名称(productname)查询相应的成品信息,具体的代码如下:
复制代码 代码如下:

protected void page_load(object sender, eventargs e)
{
if (!page.ispostback)
{
// gets product id from table production.product.
// then binding data to drop down list control.
initcontrol(getproductid());
}
}
/// <summary>
/// handles the click event of the btnsubmit control.
/// redirects to relative product information page.
/// </summary>
protected void btnsubmit_click(object sender, eventargs e)
{
response.redirect(string.format("product.aspx?productname={0}", ddlproductname.selectedvalue));
}

当用户点击submit按钮后,跳转到product页面并且在url中传递查询参数——产品名称(producname)。

接下来,我们继续完成查询页面,由于在前一页面中传递了查询参数productname,那么我们将根据productname查询数据库获取相应的产品信息,具体代码如下所示:
复制代码 代码如下:

protected void page_load(object sender, eventargs e)
{
// get product name.
string productname = request.querystring["productname"];

// binding data to data grid view control.
initcontrol(this.getdata(productname));
}

/// <summary>
/// inits the control.
/// </summary>
/// <param name="ds">the dataset.</param>
private void initcontrol(dataset ds)
{
dgvproduct.datasource = ds;
dgvproduct.databind();
}

/// <summary>
/// gets the data.
/// </summary>
/// <param name="productname">name of the product.</param>
/// <returns>returns dataset</returns>
private dataset getdata(string productname)
{
// the query sql base on product name.
string sql =
string.format(
"select name, productnumber, safetystocklevel, reorderpoint, standardcost, daystomanufacture "
+ "from production.product where productnumber='{0}'",
productname);

// get data from table production.product.
using (var con = new sqlconnection(configurationmanager.connectionstrings["sqlconn"].tostring()))
using (var com = new sqlcommand(sql, con))
{
com.connection.open();
////gdvdata.datasource = com.executereader();
////gdvdata.databind();
var ada = new sqldataadapter(com);
var ds = new dataset();
ada.fill(ds);
return ds;
}
}

前面示例,我们通过request的属性querystring获取productname的值,然后根据productname查询数据库,最后把获取数据绑定到datagridview控件中(注:前面实例没有考虑sql injection问题)。

cache3

图3查询结果

现在我们在页面中添加输出缓存,如下代码:
复制代码 代码如下:

<!-- adds outputcache directive -->
<%@ outputcache duration="30" varybyparam="none" %>

前面提到当输出缓存的属性varybyparam=”none”时,asp.net程序在缓存有效期内只缓存一个页面副本;现在我们在缓存有效期内(30s)再发送请求。

cache4



图4查询结果

通过上图我们发现,现在查询参数productname=bk-m18b-40,但查询结果依然是productname=bb-9108的数据,这是由于asp.net程序在缓存有效期内只缓存一个页面副本。

通过上面的示例,我们发现只缓存一个页面是不适用包含查询参数的页面输出缓存;其实前面的示例我们只需稍稍改动就能符合查询参数的情况了,想必大家已经知道了,只需把varybyparam属性设置为“*”就ok了。

cache5

cache6

图5查询结果

现在查询可以获取相应的结果,如果查询参数和前一个请求相同并且该页面缓存有效,那么缓存将被重用,否则,创建一个新的页面缓存。

由于asp.net给每个查询参数都添加了输出缓存,但我们要注意的是是否真的有必要缓存每个查询参数都缓存一个页面副本,假设查询url中增加一个参数参数productid,那么现在url中就有两个查询参数了(productname和productid)。

前面我们把varybyparam设置为“*”,所为asp.net程序对productname和productid都创建页面缓存,如果我们只针对productname创建页面缓存,这时我们可以修改varybyparam,具体如下所示:
复制代码 代码如下:

<!-- sets varybyparam property-->
<%@ outputcache duration="30" varybyparam="productname" %>

自定义缓存控件
前面我们介绍了通过查询参数实现缓存一个或多个页面,其实asp.net也允许我们自定义缓存方式来决定是否缓存页或重用现有的,这时我们可以通过设置varybycustom属性来实现。

假设,现在我们要设计基于不同userhostname的缓存,由于程序在执行过程中,首先调用全局方法getvarybycustomstring()来确定是否缓存页面或重用现有的,所以我们可以通过重写getvarybycustomstring()方法实现基于userhostname的缓存,首先我们创建一个global.asax文件然后重新全局方法getvarybycustomstring()具体实现如下:
复制代码 代码如下:

/// <summary>
/// gets vary cache based on custom string value.
/// </summary>
/// <param name="context">http context.</param>
/// <param name="custom">custom string</param>
/// <returns></returns>
public override string getvarybycustomstring(httpcontext context, string custom)
{
if (string.equals(custom, "userhostname", stringcomparison.ordinalignorecase))
{
// indicates that the cache should be vary on user host name.
return context.request.userhostname;
}
return base.getvarybycustomstring(context, custom);
}

前面我们重写了getvarybycustomstring()方法,使得userhostname值不同时,获取相应的缓存值。

然后让程序基于userhostname创建缓存,所以我们要在页面添加以下代码:
复制代码 代码如下:

<!-- set vary cache based on custom string value -->
<%@ outputcache duration="30" varybyparam="none" varybycustom="userhostname" %>

我们通过自定义现在getvarybycustomstring()方法,实现了web程序根据userhostname实施不同的缓存方式,其实,我们还可以实现更多种类缓存方案,例如:基于用户角色、时间和url等等。

片段缓存
在某些情况下,我们不能缓存整个页面,但我们仍想缓存部分页面从而减轻系统的负担;其实,我们可以通过两种方法实现:片段缓存和数据缓存.

为了实现片段缓存,我们需要创建自定义控件缓存部分页面,然后我们把outputcache指令添加到自定义控件中,这样整个页面将不会被缓存,而自定义缓存控件除外。

前面我们介绍了输出缓存的使用,只需在页面中添加outputcache指令,假设我们要在几个页面中添加输出缓存这可能比较简单,但我们要在几十个页面中添加输出缓存功能,而且前面介绍的例子中duration属性值都是直接hard code到每个页面中,如果我们需要修改duration属性值,那么就必须修改每个页面了,asp.net还需要重新编译这些页面,这不利于我们的维护,最重要的是增加了我们的工作量。

其实,我们可以在web.config文件中定义一个outputcacheprofile(productcacheprofile),然后在页面中添加cacheprofile属性并且赋值为productcacheprofile,web.config文件设置如下:
复制代码 代码如下:

<caching>
<!-- sets out put cache profile-->
<outputcachesettings>
<outputcacheprofiles>
<add name="productcacheprofile" duration="30"/>
</outputcacheprofiles>
</outputcachesettings>
</caching>现在,我们在页面中添加cacheprofile属性,并且设置为productcacheprofile,如下所示:

复制代码 代码如下:

<!-- set cacheprofile property -->
<%@ outputcache cacheprofile="productcacheprofile" varybyparam="none" %>

数据缓存
cache对象是线程安全:这表示无需显式实现锁定或解锁,在添删cache对象中的元素,然而,在cache对象中元素必须是线程安全的。例如,我们创建一个实体product,而且存在多个客户端可能同时操作该对象的情况,这时我们必须为实体product实现锁定和解锁操作(同步操作请参考《单例模式(singleton)的6种实现》)。

cache对象中的缓存项自动移除:当缓存过期,依赖项被修改或内存不足缓存asp.net会自动移除该缓存项。

缓存项支持依赖关系:我们可以给缓存项添加文件、数据库表或其他资源类型的依赖关系。

sqldatasource缓存
当我们在sqldatasource控件中启用缓存,它缓存selectcommand中的结果;如果sql查询语句中带有参数时,sqldatasource控件会缓存每一个参数值对应的结果。

这跟我们之前通过输出缓存实现报表程序缓存查询页面效果一样,所以我们将使用sqldatasource缓存实现该效果。

假设我们要提供一个报表程序,让用户通过选择产品名称(productname),获取相应的产品信息。

首先,我们在页面中创建两个数据源控件:sourceproductname和sourceproduct,接着把数据源分别绑定到dropdownlist和gridview中,具体实现如下:
复制代码 代码如下:

<!-- the product number datasource start -->
<asp:sqldatasource id="sourceproductname" runat="server" providername="system.data.sqlclient"
enablecaching="true" cacheduration="3600" connectionstring="<%$ connectionstrings:sqlconn %>"
selectcommand="select productnumber from production.product"></asp:sqldatasource>
<!-- the product number datasource end -->

<!-- the product datasource start -->
<asp:sqldatasource id="sourceproduct" runat="server" providername="system.data.sqlclient"
enablecaching="true" cacheduration="3600" connectionstring="<%$ connectionstrings:sqlconn %>"
selectcommand="select name, productnumber, safetystocklevel, reorderpoint, standardcost, daystomanufacture
from production.product where productnumber=@productnumber">
<selectparameters>
<asp:controlparameter controlid="ddlproductnumber" name="productnumber" propertyname="selectedvalue" />
</selectparameters>
</asp:sqldatasource>
<!-- the product number datasource end -->

<!-- binding the product number to gridview control -->
<!-- note: due to search and result in the same page, so need to set autopostback is true-->
<asp:dropdownlist id="ddlproductnumber" autopostback="true" datasourceid="sourceproductname"
datatextfield="productnumber" runat="server">
</asp:dropdownlist>

<!-- binding the product datasource to gridview control -->
<asp:gridview id="gvproduct" runat="server" datasourceid="sourceproduct" cssclass="product">
</asp:gridview>

现在我们对报表程序进行查询,如果proudctname之前没有被缓存起来就会创建相应的缓存,而已经缓存起来的将被重用,查询结果如下:

cache8
图6查询结果

缓存的依赖关系
缓存项之间的依赖

asp.net cache允许我们建立缓存之间的依赖关系,即一个缓存项依赖于另一个缓存项;以下示例代码创建了二个缓存项,并且它们之间建立依赖关系。具体实现如下:
复制代码 代码如下:

// creates cache object key1.
cache["key1"] = "cache item 1";

// makes cache["key2"] dependent on cache["key1"].
string[] dependencykey = new string[1];
dependencykey[0] = "key1";

// creates a cachedependency object.
cachedependency dependency = new cachedependency(null, dependencykey);

// establishs dependency between cache key1 and key2.
cache.insert("key2", "cache item 2", dependency);

现在,当key1缓存项更新或从缓存中删除,key2缓存项就会自动从缓存删除。

文件依赖

前面我们介绍了缓存项之间的依赖关系,asp.net cache还提供缓存项与文件之间的依赖关系,当文件被更新或删除对应的缓存项也将失效。

在上篇博文《ajax与json的一些总结》的最后介绍的一个demo——weibo feed中,我们通过实时方式向新浪微博api发送请求获取相应的数据,但在一定时间内请求的次数是有限制的,一旦超出了限制次数就不再接受请求了(具体请参考rate-limiting)。所以可以通过cache的方式把数据缓存起来,当客户端请求时,如果缓存数据已经存在那么直接返回数据,否则重新想微博api请求数据。

首先,我们创建一个httphandler,它负责向微博api发送请求并且把数据保存的文件中,最后把数据返回的客户端。

cache9

图7 请求流程
接下来,我们定义cachedata()方法把微博数据保存到文本文件中并且建立缓存与数据文件的依赖关系。
复制代码 代码如下:

/// <summary>
/// caches the data into text file.
/// </summary>
/// <param name="context">the http context</param>
private void cachedata(httpcontext context)
{
// weibo api.
string uri = context.request.querystring["api"] + "?" +
"source=" + context.request.querystring["source"] + "&" +
"count=" + context.request.querystring["count"];
httpwebresponse response = this.getweibos(uri);
if (null == response)
{
throw new argumentnullexception("response is null");
}
string jsondata;
// writes the reponse data into text file.
using (var reader = new streamreader(response.getresponsestream(), encoding.getencoding(response.characterset)))
{
jsondata = reader.readtoend();
}
string datapath = context.server.mappath("weibo.json");
using (var writer = new streamwriter(datapath, false, encoding.getencoding(response.characterset)))
{
writer.write(jsondata);
}
// establishs dependency between cache weibo and text file.
// sets cache expires after 2 minuntes.
httpruntime.cache.insert("weibo", jsondata, dep, cache.noabsoluteexpiration, timespan.fromminutes(2));
}

现在我们把数据保存到文本文件中并且建立了缓存weibo与数据文件的依赖关系,接下来我们要把json格式数据返回给客户端。
复制代码 代码如下:

/// <summary>
/// responses the weibo data.
/// </summary>
/// <param name="context">the http contex.</param>
private void responseweibo(httpcontext context)
{
// gets the weibo cache data.
byte[] buf = encoding.utf8.getbytes(httpruntime.cache["weibo"].tostring());
// writes the data into output stream.
context.response.outputstream.write(buf, 0, buf.length);
context.response.outputstream.flush();
////context.response.close();
}

上面我们把json格式字符串转换为byte数值,然后写入到outputstream中,最后把数据返回给客户端。
复制代码 代码如下:

// the function to get weibo data.
loadweibo: function() {
$.ajax({
// weibo api.
url: "weibohandler.ashx",
type: "get",
// note: we get the data from same domain,
// datatype is json.
datatype: "json",
data: {
source: jqweibo.appkey,
count: jqweibo.numweibo
},
// when the requet completed, then invokes success function.
success: function(data, textstatus, xhr) {
// sets html structure.
var html =
'<div class="weibo">' +
'<a href="http://weibo.com/domain" target="_blank">user</a>' +
':weibo_text<div class="time">ago</div>';
// appends weibos into html page.
for (var i = 0; i < data.length; i++) {
$(jqweibo.appendto).append(
html.replace('weibo_text', jqweibo.ify.clean(data[i].text))
// uses regex and declare domain as global, if found replace all.
.replace(/domain/g, data[i].user.domain)
.replace(/user/g, data[i].user.screen_name)
.replace('ago', jqweibo.timeago(data[i].created_at))
);
}
}
})
}

cache10图8请求结果
1.1.3 总结
缓存可以使应用程序的性能得到很大的提高,因此在设计应用程序应该予以考虑,本博文主要介绍了asp.net中输出缓存和数据缓存的应用场合和区别。

页面缓存适用于生成的页面通常都相同或改变时间比较固定情况,例如:数据在每小时都会更新,那么我们可以设置duration为3600s。

数据缓存适用生成的页面总是在变化情况。



如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网