欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ASP.NET 提高首頁(yè)性能的十大做法

 更新時(shí)間:2010年05月06日 23:11:48   作者:  
本文是我對(duì)ASP.NET頁(yè)面載入速度提高的一些做法,這些做法分為以下部分,希望對(duì)朋友們有所幫助。
前言
本文是我對(duì)ASP.NET頁(yè)面載入速度提高的一些做法,這些做法分為以下部分:
1.采用 HTTP Module 控制頁(yè)面的生命周期。
2.自定義Response.Filter得到輸出流stream生成動(dòng)態(tài)頁(yè)面的靜態(tài)內(nèi)容(磁盤(pán)緩存)。
3.頁(yè)面GZIP壓縮。
4.OutputCache 編程方式輸出頁(yè)面緩存。
5.刪除頁(yè)面空白字符串。(類(lèi)似Google)
6.完全刪除ViewState。
7.刪除服務(wù)器控件生成的垃圾NamingContainer。
8.使用計(jì)劃任務(wù)按時(shí)生成頁(yè)面。(本文不包含該做法的實(shí)現(xiàn))
9.JS,CSS壓縮、合并、緩存,圖片緩存。(限于文章篇幅,本文不包含該做法的實(shí)現(xiàn))
10.緩存破壞。(不包含第9做法的實(shí)現(xiàn))

針對(duì)上述做法,我們首先需要一個(gè) HTTP 模塊,它是整個(gè)頁(yè)面流程的入口和核心。

一、自定義Response.Filter得到輸出流stream生成動(dòng)態(tài)頁(yè)面的靜態(tài)內(nèi)容(磁盤(pán)緩存)
如下的代碼我們可以看出,我們以 request.RawUrl 為緩存基礎(chǔ),因?yàn)樗梢园我獾腝ueryString變量,然后我們用MD5加密RawUrl 得到服務(wù)器本地文件名的變量,再實(shí)例化一個(gè)FileInfo操作該文件,如果文件最后一次生成時(shí)間小于7天,我們就使用.Net2.0新增的TransmitFile方法將存儲(chǔ)文件的靜態(tài)內(nèi)容發(fā)送到瀏覽器。如果文件不存在,我們就操作 response.Filter 得到的 Stream 傳遞給 CommonFilter 類(lèi),并利用FileStream寫(xiě)入動(dòng)態(tài)頁(yè)面的內(nèi)容到靜態(tài)文件中。
復(fù)制代碼 代碼如下:

namespace ASPNET_CL.Code.HttpModules {
public class CommonModule : IHttpModule {
public void Init( HttpApplication application ) {
application.BeginRequest += Application_BeginRequest;
}
private void Application_BeginRequest( object sender, EventArgs e ) {
var context = HttpContext.Current;
var request = context.Request;
var url = request.RawUrl;
var response = context.Response;
var path = GetPath( url );
var file = new FileInfo( path );
if ( DateTime.Now.Subtract( file.LastWriteTime ).TotalDays < 7 ) {
response.TransmitFile( path );
response.End();
return;
}
try {
var stream = file.OpenWrite();
response.Filter = new CommonFilter( response.Filter, stream );
}
catch ( Exception ) {
//Log.Insert("");
}
}
public void Dispose() {
}
private static string GetPath( string url ) {
var hash = Hash( url );
string fold = HttpContext.Current.Server.MapPath( "~/Temp/" );
return string.Concat( fold, hash );
}
private static string Hash( string url ) {
url = url.ToUpperInvariant();
var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
var bs = md5.ComputeHash( Encoding.ASCII.GetBytes( url ) );
var s = new StringBuilder();
foreach ( var b in bs ) {
s.Append( b.ToString( "x2" ).ToLower() );
}
return s.ToString();
}
}
}


二、頁(yè)面GZIP壓縮
對(duì)頁(yè)面GZIP壓縮幾乎是每篇講解高性能WEB程序的幾大做法之一,因?yàn)槭褂肎ZIP壓縮可以降低服務(wù)器發(fā)送的字節(jié)數(shù),能讓客戶(hù)感覺(jué)到網(wǎng)頁(yè)的速度更快也減少了對(duì)帶寬的使用情況。當(dāng)然,這里也存在客戶(hù)端的瀏覽器是否支持它。因此,我們要做的是,如果客戶(hù)端支持GZIP,我們就發(fā)送GZIP壓縮過(guò)的內(nèi)容,如果不支持,我們直接發(fā)送靜態(tài)文件的內(nèi)容。幸運(yùn)的是,現(xiàn)代瀏覽器IE6.7.8.0,火狐等都支持GZIP。
為了實(shí)現(xiàn)這個(gè)功能,我們需要改寫(xiě)上面的 Application_BeginRequest 事件:
復(fù)制代碼 代碼如下:

private void Application_BeginRequest( object sender, EventArgs e ) {
var context = HttpContext.Current;
var request = context.Request;
var url = request.RawUrl;
var response = context.Response;
var path = GetPath( url );
var file = new FileInfo( path );
// 使用頁(yè)面壓縮
ResponseCompressionType compressionType = this.GetCompressionMode( request );
if ( compressionType != ResponseCompressionType.None ) {
response.AppendHeader( "Content-Encoding", compressionType.ToString().ToLower() );
if ( compressionType == ResponseCompressionType.GZip ) {
response.Filter = new GZipStream( response.Filter, CompressionMode.Compress );
}
else {
response.Filter = new DeflateStream( response.Filter, CompressionMode.Compress );
}
}
if ( DateTime.Now.Subtract( file.LastWriteTime ).TotalMinutes < 5 ) {
response.TransmitFile( path );
response.End();
return;
}
try {
var stream = file.OpenWrite();
response.Filter = new CommonFilter( response.Filter, stream );
}
catch ( Exception ) {
//Log.Insert("");
}
}
private ResponseCompressionType GetCompressionMode( HttpRequest request ) {
string acceptEncoding = request.Headers[ "Accept-Encoding" ];
if ( string.IsNullOrEmpty( acceptEncoding ) )
return ResponseCompressionType.None;
acceptEncoding = acceptEncoding.ToUpperInvariant();
if ( acceptEncoding.Contains( "GZIP" ) )
return ResponseCompressionType.GZip;
else if ( acceptEncoding.Contains( "DEFLATE" ) )
return ResponseCompressionType.Deflate;
else
return ResponseCompressionType.None;
}
private enum ResponseCompressionType {
None,
GZip,
Deflate
}

三、OutputCache 編程方式輸出頁(yè)面緩存
ASP.NET內(nèi)置的 OutputCache 緩存可以將內(nèi)容緩存在三個(gè)地方:Web服務(wù)器、代理服務(wù)器和瀏覽器。當(dāng)用戶(hù)訪問(wèn)一個(gè)被設(shè)置為 OutputCache的頁(yè)面時(shí),ASP.NET在MSIL之后,先將結(jié)果寫(xiě)入output cache緩存,然后在發(fā)送到瀏覽器,當(dāng)用戶(hù)訪問(wèn)同一路徑的頁(yè)面時(shí),ASP.NET將直接發(fā)送被Cache的內(nèi)容,而不經(jīng)過(guò).aspx編譯以及執(zhí)行MSIL的過(guò)程,所以,雖然程序的本身效率沒(méi)有提升,但是頁(yè)面載入速度卻得到了提升。

為了實(shí)現(xiàn)這個(gè)功能,我們繼續(xù)改寫(xiě)上面的 Application_BeginRequest 事件,我們?cè)?TransmitFile 后,將這個(gè)路徑的頁(yè)面以O(shè)utputCache編程的方式緩存起來(lái):
復(fù)制代碼 代碼如下:

private void Application_BeginRequest( object sender, EventArgs e ) {
//.............
if ( DateTime.Now.Subtract( file.LastWriteTime ).TotalMinutes < 5 ) {
response.TransmitFile( path );
// 添加 OutputCache 緩存頭,并緩存在客戶(hù)端
response.Cache.SetExpires( DateTime.Now.AddMinutes( 5 ) );
response.Cache.SetCacheability( HttpCacheability.Public );
response.End();
return;
}
//............
}

四、實(shí)現(xiàn)CommonFilter類(lèi)過(guò)濾ViewState、過(guò)濾NamingContainer、空白字符串,以及生成磁盤(pán)的緩存文件
我們傳入response.Filter的Stream對(duì)象給CommonFilter類(lèi):
首先,我們用先Stream的Write方法實(shí)現(xiàn)生成磁盤(pán)的緩存文件,代碼如下,在這些代碼中,只有初始化構(gòu)造函數(shù),Write方法,Close方式是有用的,其中FileStream字段是生成靜態(tài)文件的操作對(duì)象:
復(fù)制代碼 代碼如下:

namespace ASPNET_CL.Code.HttpModules {
public class CommonFilter : Stream {
private readonly Stream _responseStream;
private readonly FileStream _cacheStream;
public override bool CanRead {
get {
return false;
}
}
public override bool CanSeek {
get {
return false;
}
}
public override bool CanWrite {
get {
return _responseStream.CanWrite;
}
}
public override long Length {
get {
throw new NotSupportedException();
}
}
public override long Position {
get {
throw new NotSupportedException();
}
set {
throw new NotSupportedException();
}
}
public CommonFilter( Stream responseStream, FileStream stream ) {
_responseStream = responseStream;
_cacheStream = stream;
}
public override long Seek( long offset, SeekOrigin origin ) {
throw new NotSupportedException();
}
public override void SetLength( long length ) {
throw new NotSupportedException();
}
public override int Read( byte[] buffer, int offset, int count ) {
throw new NotSupportedException();
}
public override void Flush() {
_responseStream.Flush();
_cacheStream.Flush();
}
public override void Write( byte[] buffer, int offset, int count ) {
_cacheStream.Write( buffer, offset, count );
_responseStream.Write( buffer, offset, count );
}
public override void Close() {
_responseStream.Close();
_cacheStream.Close();
}
protected override void Dispose( bool disposing ) {
if ( disposing ) {
_responseStream.Dispose();
_cacheStream.Dispose();
}
}
}
}

然后我們利用正則完全刪除ViewState:
復(fù)制代碼 代碼如下:

// 過(guò)濾ViewState
private string ViewStateFilter( string strHTML ) {
string matchString1 = "type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\"";
string matchString2 = "type=\"hidden\" name=\"__EVENTVALIDATION\" id=\"__EVENTVALIDATION\"";
string matchString3 = "type=\"hidden\" name=\"__EVENTTARGET\" id=\"__EVENTTARGET\"";
string matchString4 = "type=\"hidden\" name=\"__EVENTARGUMENT\" id=\"__EVENTARGUMENT\"";
string positiveLookahead1 = "(?=.*(" + Regex.Escape( matchString1 ) + "))";
string positiveLookahead2 = "(?=.*(" + Regex.Escape( matchString2 ) + "))";
string positiveLookahead3 = "(?=.*(" + Regex.Escape( matchString3 ) + "))";
string positiveLookahead4 = "(?=.*(" + Regex.Escape( matchString4 ) + "))";
RegexOptions opt = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.Compiled;
Regex[] arrRe = new Regex[] {
new Regex("\\s*<div>" + positiveLookahead1 + "(.*?)</div>\\s*", opt),
new Regex("\\s*<div>" + positiveLookahead2 + "(.*?)</div>\\s*", opt),
new Regex("\\s*<div>" + positiveLookahead3 + "(.*?)</div>\\s*", opt),
new Regex("\\s*<div>" + positiveLookahead3 + "(.*?)</div>\\s*", opt),
new Regex("\\s*<div>" + positiveLookahead4 + "(.*?)</div>\\s*", opt)
};
foreach ( Regex re in arrRe ) {
strHTML = re.Replace( strHTML, "" );
}
return strHTML;
}

以下是刪除頁(yè)面空白的方法:
復(fù)制代碼 代碼如下:

// 刪除空白
private Regex tabsRe = new Regex( "\\t", RegexOptions.Compiled | RegexOptions.Multiline );
private Regex carriageReturnRe = new Regex( ">\\r\\n<", RegexOptions.Compiled | RegexOptions.Multiline );
private Regex carriageReturnSafeRe = new Regex( "\\r\\n", RegexOptions.Compiled | RegexOptions.Multiline );
private Regex multipleSpaces = new Regex( " ", RegexOptions.Compiled | RegexOptions.Multiline );
private Regex spaceBetweenTags = new Regex( ">\\s<", RegexOptions.Compiled | RegexOptions.Multiline );
private string WhitespaceFilter( string html ) {
html = tabsRe.Replace( html, string.Empty );
html = carriageReturnRe.Replace( html, "><" );
html = carriageReturnSafeRe.Replace( html, " " );
while ( multipleSpaces.IsMatch( html ) )
html = multipleSpaces.Replace( html, " " );
html = spaceBetweenTags.Replace( html, "><" );
html = html.Replace( "http://<![CDATA[", "" );
html = html.Replace( "http://]]>", "" );
return html;
}

以下是刪除ASP.NET控件的垃圾UniqueID名稱(chēng)方法:
復(fù)制代碼 代碼如下:

// 過(guò)濾NamingContainer
private string NamingContainerFilter( string html ) {
RegexOptions opt =
RegexOptions.IgnoreCase |
RegexOptions.Singleline |
RegexOptions.CultureInvariant |
RegexOptions.Compiled;
Regex re = new Regex( "( name=\")(?=.*(" + Regex.Escape( "$" ) + "))([^\"]+?)(\")", opt );
html = re.Replace( html, new MatchEvaluator( delegate( Match m ) {
int lastDollarSignIndex = m.Value.LastIndexOf( '$' );
if ( lastDollarSignIndex >= 0 ) {
return m.Groups[ 1 ].Value + m.Value.Substring( lastDollarSignIndex + 1 );
}
else {
return m.Value;
}
} ) );
return html;
}

最后,我們把以上過(guò)濾方法整合到CommonFilter類(lèi)的Write方法:
復(fù)制代碼 代碼如下:

public override void Write( byte[] buffer, int offset, int count ) {
// 轉(zhuǎn)換buffer為字符串
byte[] data = new byte[ count ];
Buffer.BlockCopy( buffer, offset, data, 0, count );
string html = System.Text.Encoding.UTF8.GetString( buffer );
//
// 以下整合過(guò)濾方法
//
html = NamingContainerFilter( html );
html = ViewStateFilter( html );
html = WhitespaceFilter( html );
byte[] outdata = System.Text.Encoding.UTF8.GetBytes( html );
// 寫(xiě)入磁盤(pán)
_cacheStream.Write( outdata, 0, outdata.GetLength( 0 ) );
_responseStream.Write( outdata, 0, outdata.GetLength( 0 ) );
}

五、緩存破壞
經(jīng)過(guò)以上程序的實(shí)現(xiàn),網(wǎng)頁(yè)已經(jīng)被高速緩存在客戶(hù)端了,如果果用戶(hù)訪問(wèn)網(wǎng)站被緩存過(guò)的頁(yè)面,則頁(yè)面會(huì)以0請(qǐng)求的速度加載頁(yè)面。但是,如果后臺(tái)更新了某些數(shù)據(jù),前臺(tái)用戶(hù)則不能及時(shí)看到最新的數(shù)據(jù),因此要改變這種情況,我們必須破壞緩存。根據(jù)我們?nèi)缟系某绦?,我們破壞緩存只需要?步:更新服務(wù)器上的臨時(shí)文件,刪除OutputCache過(guò)的頁(yè)面。

更新服務(wù)器上的文件我們只需刪除這個(gè)文件即可,當(dāng)某一用戶(hù)第一次訪問(wèn)該頁(yè)面時(shí)會(huì)自動(dòng)生成,當(dāng)然,你也可以用程序先刪除后生成:
復(fù)制代碼 代碼如下:

// 更新文件
foreach ( var file in Directory.GetFiles( HttpRuntime.AppDomainAppPath + "Temp" ) ) {
File.Delete( file );
}

要?jiǎng)h除OutputCache關(guān)聯(lián)的緩存項(xiàng),代碼如下,我們只需要保證該方法的參數(shù),指頁(yè)面的絕對(duì)路徑是正確的,路徑不能使用../這樣的相對(duì)路徑:
復(fù)制代碼 代碼如下:

// 刪除緩存
HttpResponse.RemoveOutputCacheItem( "/Default.aspx" );

到此,我們實(shí)現(xiàn)了針對(duì)一個(gè)頁(yè)面的性能,重點(diǎn)是載入速度的提高的一些做法,希望對(duì)大家有用~!

相關(guān)文章

最新評(píng)論