減少往返
將內容移到離客戶端更近的地方
避免為重復的內容,花費再次請求的時間
在所有層緩存,一般應用有以下層次:
1、瀏覽器
2、本地代理-isp代理
3、web服務器中:
http.sys
iis輸出緩存
ASP.NET輸出緩存
ASP.NET對象緩存、ASP.NET請求緩存
4、SQLSERVER數據庫
我們盡可能合理地在每一層中進行緩存
瀏覽器緩存
減少服務器之間的往返,縮短相應時間.
緩存靜態內容:在http頭信息中,cache-control屬性表示緩存信息。
設置cache-control屬性,可以在IIS管理器中設置cache-control的值,還可以在Web.Config文件中配置:
<system.webserver>
<staticContent>
<clientCache cacheControlAge="usage" cacheControlMaxage="365.00:00:00"/>
</staticContent>
</system.webserver>
在后面還可以為特定的靜態資源,設置更短的時間。
關閉游覽器緩存
可以為特定的靜態資源關閉瀏覽器緩存,可以在IIS中設置,也可以在Web.Config文件中配置:
<location path="image.jpg">
<system.webserver>
<staticContent>
<clientCache cacheControlMode="DisableCache"/>
</staticContent>
</system.webserver>
</location>
緩存動態內容
在ASPX頁面中使用聲明方式實現緩存,設置過期時間:
<%@outputcache Duration="86400" Location="client" VaryByParam="None"%>
這句話在運行時中會生成Http頭,讓瀏覽器緩存86400秒(1天),還必須設置VaryByParam="None"屬性,表明該頁面的多個版本不需要獨立緩存。
還可以通過編程方式設置,在后置代碼或者httpModule中:
void SetCache()
{
this.Response.Cache.SetExpires(DateTime.Now.AddDays(1));//可以忽略
TimeSpane ds = new TimeSpane(1,0,0,0);
this.Response.Cache.SetMaxage(ds);//關鍵代碼
}
使用緩存配置
在Web.Config文件中配置一個緩存,然后可以在ASPX里面outputcache中使用:
<system.web>
<caching>
<outputcachesetting>
<outputcacheprofiles>
<add name="cacheDay" duration="86400" location="client" varyByParam="none"/>
</outputcacheprofiles>
</outputcachesetting>
</caching>
</system.web>
在ASPX頁面中:
<%@outputcache cacheprofile="cacheDay"%>
也能達到一樣的目的。
關閉緩存
應該只在數據必須時刻保持最新的情況下,關閉緩存。
關閉緩存只能在編程的時候實現:
void SetNoCache()
{
this.Response.Cache.SetCacheablity(HttpCacheablity.Nocache);//關鍵代碼
}