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