本文將介紹一些方法用于優化ASP.NET網站性能,這些方法都是不需要修改程序代碼的。它們主要分為二個方面:1. 利用ASP.NET自身的擴展性進行優化。2. 優化IIS設置。
用緩存來優化網站性能的方法,估計是無人不知的。 ASP.NET提供了HttPRuntime.Cache對象來緩存數據,也提供了OutputCache指令來緩存整個頁面輸出。雖然OutputCache指令使用起來更方便,也有非常好的效果,不過,它需要我們在那些頁面中添加這樣一個指令。
對于設置過OutputCache的頁面來說,瀏覽器在收到這類頁面的響應后,會將頁面響應內容緩存起來。只要在指定的緩存時間之內,且用戶沒有強制刷新的操作,那么就根本不會再次請求服務端,而對于來自其它的瀏覽器發起的請求,如果緩存頁已生成,那么就可以直接從緩存中響應請求,加快響應速度。因此,OutputCache指令對于性能優化來說,是很有意義的(除非所有頁面頁面都在頻繁更新)。
在網站的優化階段,我們可以用Fiddler之類的工具找出一些內容幾乎不會改變的頁面,給它們設置OutputCache,但是,按照傳統的開發流程,我們需要針對每個頁面文件執行以下操作:
1. 簽出頁面文件。
2. 添加OutputCache指令。
3. 重新發布頁面。
4. 簽入文件(如果遇到多分支并行,還可能需要合并操作)。
以上這些源代碼管理制度會讓一個簡單的事情復雜化,那么,有沒一種更簡單的方法能解決這個問題呢?
接下來,本文將介紹一種方法,它利用ASP.NET自身的擴展性,以配置文件的方式為頁面設置OutputCache參數。配置文件其它就是一個xml文件,內容如下:
12345678 | <? xml version = "1.0" encoding = "utf-8" ?> < OutputCache xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd = "http://www.w3.org/2001/XMLSchema" >
< Settings >
< Setting Duration = "3" FilePath = "/Pages/a3.aspx" />
< Setting Duration = "10" FilePath = "/Pages/a5.aspx" />
</ Settings > </ OutputCache > |
看了這段配置,我想您應該也能猜到它能有什么作用。
每一行配置參數為一個頁面指定OutputCache所需要的參數,示例文件為了簡單只使用二個參數,其它可以支持的參數請參考OutputCache指令。
為了能讓這個配置文件有效,需要在web.config中配置以下內容(適用于IIS7):
12345 | < system.webServer >
< modules >
< add name = "SetOutputCacheModule" type = "WebSiteOptimize.SetOutputCacheModule, WebSiteOptimize" />
</ modules > </ system.webServer > |
在這里,我注冊了一個HttpModule,它的全部代碼如下:
1234567891011121314151617181920212223242526272829 | public class SetOutputCacheModule : IHttpModule {
static SetOutputCacheModule()
{
// 加載配置文件
string xmlFilePath = Path.Combine(HttpRuntime.AppDomainAppPath, "OutputCache.config" );
ConfigManager.LoadConfig(xmlFilePath);
}
public void Init(Httpapplication app)
{
app.PreRequestHandlerExecute += new EventHandler(app_PreRequestHandlerExecute);
}
void app_PreRequestHandlerExecute( object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
Dictionary< string , OutputCacheSetting> settings = ConfigManager.Settings;
if ( settings == null )
throw new ConfigurationErrorsException( "SetOutputCacheModule加載配置文件失敗。" );
// 實現方法:
// 查找配置參數,如果找到匹配的請求,就設置OutputCache
OutputCacheSetting setting = null ;
if ( settings.TryGetValue(app.Request.FilePath, out setting) ) {
setting.SetResponseCache(app.Context);
}
} |
ConfigManager類用于讀取配置文件,并啟用了文件依賴技術,當配置文件更新后,程序會自動重新加載: