ASP.NET數(shù)據(jù)緩存機(jī)制淺析
ASP.NET數(shù)據(jù)緩存機(jī)制主要是什么呢?讓我們開始我們的講解:
◆頁(yè)輸出緩存:保存頁(yè)處理輸出,下次重用所保存的輸出
◆應(yīng)用程序緩存:允許緩存所生成的數(shù)據(jù),如DataSet
㈠ASP.NET數(shù)據(jù)緩存頁(yè)輸出緩存
1、ASP.NET數(shù)據(jù)緩存頁(yè)輸出緩存的幾中形式
① ﹤%@ OutputCache Duration= "60 " VaryByParam= "None " Location= "Any "%﹥
Location指定在哪個(gè)地方緩存,Any任何地方都緩存。
60秒以內(nèi)看到的都是一樣的了。
②還可在配置文件里寫,然后在頁(yè)面調(diào)用配置文件的緩存名稱。
③用編程的方式:
- Response.Canche.SetExpires(DateTime.Now.AddSeconds(3));
- Response.Canche.SetCacheabiliy(HttpCacheability.Public);
- Response.Canche.SetValidUntilExpires(true);
相當(dāng)于:
- Public =﹥ Any
- Private =﹥ Client
- NoCache =﹥ None
- Server =﹥ Server
- ServerAndPrivate =﹥ ServerAndClient
2、ASP.NET數(shù)據(jù)緩存使用文件依賴項(xiàng)緩存頁(yè)輸出
產(chǎn)生背景:有時(shí)候,可能需要在文件發(fā)生更改時(shí)從輸出緩存中移除某一項(xiàng)。就是說文件改了以后緩存立即失效。
- string filepath = Server.MapPath( "TextFile1.txt ");
- Response.AddFileDependency(filepath);//添加緩存依賴項(xiàng)
- Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
- Response.Cache.SetCacheability(HttpCacheability.Public);
- Response.Cache.SetValidUntiExpires(true);
3、ASP.NET數(shù)據(jù)緩存緩存多個(gè)版本
①使用請(qǐng)求的瀏覽器對(duì)頁(yè)的各個(gè)版本進(jìn)行緩存
- ﹤%@OutputCache Duration= "10 " VaryByParam= "None " VaryByCustom= "browser "%﹥
②使用參數(shù)對(duì)頁(yè)的各個(gè)版本進(jìn)行緩存
- ﹤%@OutputCache Duration= "60 " VaryByParam= "City "%﹥
這個(gè)調(diào)試可以在url后加QueryString
如:...url?City=shanghai
程序里得到這個(gè)上海然后再做其他的操作,這個(gè)時(shí)候如果參數(shù)傳的還是shanghai它就不會(huì)在走到程序里了。
4、ASP.NET數(shù)據(jù)緩存動(dòng)態(tài)更新緩存頁(yè)的部分,有三種方法可以實(shí)現(xiàn)部分不緩存
①已聲明方式使用Substitution控件
- ﹤asp:Substitution ID= "Substitution1 " runat= "server " MethodName= "GetCurrentDateTime " /﹥
- public static string GetCurrentDateTime(HttpContext context)
- {
- return DateTime.Now.ToString();
- }
- //方法簽名必須和委托簽名一致
②以編程的方式使用Substitution控件API
Response.WriteSubstitution(new HttpResponseSubstitutionCallback(GetCurrentDateTime))
③以隱式方式使用AdRotator控件
這個(gè)控件永遠(yuǎn)都是不緩存的
㈡ASP.NET數(shù)據(jù)緩存SQL Server依賴的緩存,非常之有用
當(dāng)表數(shù)據(jù)發(fā)生改變就清除緩存
1、ASP.NET數(shù)據(jù)緩存為SQL Server啟用緩存通知
- aspnet_regsql.exe -S ﹤Server﹥ -U ﹤Username﹥ -P ﹤Password﹥
- -ed -d Northwind -et -t Employees
Server:服務(wù)器
Username:用戶名
Password:密碼
Northwind:數(shù)據(jù)庫(kù)
Employees:表
2、ASP.NET數(shù)據(jù)緩存為緩存功能配置網(wǎng)頁(yè)
- ﹤%@OutputCache Duration= "3600 " SqlDependency= "Northind:Employees " VaryByParam= "none "%﹥
3、ASP.NET數(shù)據(jù)緩存在Web.config文件中設(shè)置緩存配置
- ﹤caching﹥
- ﹤sqlCacheDependency enabled= "true " pollTime= "1000 "﹥
- ﹤database﹥
- ﹤add name= "Northind " connectionStringName= "... " pollTime = "1000 " /﹥
- ﹤/database﹥
- ﹤/sqlCacheDependency﹥
- ﹤/caching﹥
ASP.NET數(shù)據(jù)緩存方面的內(nèi)容就向你介紹到這里,希望對(duì)你了解ASP.NET數(shù)據(jù)緩存有所幫助。
【編輯推薦】