前言
本文是我对ASP.NET页面载入速度提高的一些做法,这些做法分为以下部分:
- 1.采用 HTTP Module 控制页面的生命周期。
- 2.自定义Response.Filter得到输出流stream生成动态页面的静态内容(磁盘缓存)。
- 3.页面GZIP压缩。
- 4.OutputCache 编程方式输出页面缓存。
- 5.删除页面空白字符串。(类似Google)
- 6.完全删除ViewState。
- 7.删除服务器控件生成的垃圾NamingContainer。
- 8.使用计划任务按时生成页面。(本文不包含该做法的实现)
- 9.JS,CSS压缩、合并、缓存,图片缓存。(限于文章篇幅,本文不包含该做法的实现)
- 10.缓存破坏。(不包含第9做法的实现)
针对上述做法,我们首先需要一个 HTTP 模块,它是整个页面流程的入口和核心。
一、自定义Response.Filter得到输出流stream生成动态页面的静态内容(磁盘缓存)
如下的代码我们可以看出,我们以 request.RawUrl 为缓存基础,因为它可以包含任意的QueryString变量,然后我们用MD5加密RawUrl 得到服务器本地文件名的变量,再实例化一个FileInfo操作该文件,如果文件最后一次生成时间小于7天,我们就使用.Net2.0新增的TransmitFile方法将存储文件的静态内容发送到浏览器。如果文件不存在,我们就操作 response.Filter 得到的 Stream 传递给 CommonFilter 类,并利用FileStream写入动态页面的内容到静态文件中。
ASPNET_CL.Code.HttpModules { CommonModule : IHttpModule { Init( HttpApplication application ) { application.BeginRequest += Application_BeginRequest; } Application_BeginRequest( 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 = FileInfo( path ); ( DateTime.Now.Subtract( file.LastWriteTime ).TotalDays < 7 ) { response.TransmitFile( path ); response.End(); ; } { var stream = file.OpenWrite(); response.Filter = CommonFilter( response.Filter, stream ); } ( Exception ) { } } Dispose() { } GetPath( url ) { var hash = Hash( url ); fold = HttpContext.Current.Server.MapPath( ); .Concat( fold, hash ); } Hash( url ) { url = url.ToUpperInvariant(); var md5 = System.Security.Cryptography.MD5CryptoServiceProvider(); var bs = md5.ComputeHash( Encoding.ASCII.GetBytes( url ) ); var s = StringBuilder(); ( var b bs ) { s.Append( b.ToString( ).ToLower() ); } s.ToString(); } } }
二、页面GZIP压缩
对页面GZIP压缩几乎是每篇讲解高性能WEB程序的几大做法之一,因为使用GZIP压缩可以降低服务器发送的字节数,能让客户感觉到网页的速度更快也减少了对带宽的使用情况。当然,这里也存在客户端的浏览器是否支持它。因此,我们要做的是,如果客户端支持GZIP,我们就发送GZIP压缩过的内容,如果不支持,我们直接发送静态文件的内容。幸运的是,现代浏览器IE6.7.8.0,火狐等都支持GZIP。
为了实现这个功能,我们需要改写上面的 Application_BeginRequest 事件:
Application_BeginRequest( 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 = FileInfo( path ); ResponseCompressionType compressionType = .GetCompressionMode( request ); ( compressionType != ResponseCompressionType.None ) { response.AppendHeader( , compressionType.ToString().ToLower() ); ( compressionType == ResponseCompressionType.GZip ) { response.Filter = GZipStream( response.Filter, CompressionMode.Compress ); } { response.Filter = DeflateStream( response.Filter, CompressionMode.Compress ); } } ( DateTime.Now.Subtract( file.LastWriteTime ).TotalMinutes < 5 ) { response.TransmitFile( path ); response.End(); ; } { var stream = file.OpenWrite(); response.Filter = CommonFilter( response.Filter, stream ); } ( Exception ) { } } ResponseCompressionType GetCompressionMode( HttpRequest request ) { acceptEncoding = request.Headers[ ]; ( .IsNullOrEmpty( acceptEncoding ) ) ResponseCompressionType.None; acceptEncoding = acceptEncoding.ToUpperInvariant(); ( acceptEncoding.Contains( ) ) ResponseCompressionType.GZip; ( acceptEncoding.Contains( ) ) ResponseCompressionType.Deflate; ResponseCompressionType.None; } ResponseCompressionType { None, GZip, Deflate }
三、OutputCache 编程方式输出页面缓存
ASP.NET内置的 OutputCache 缓存可以将内容缓存在三个地方:Web服务器、代理服务器和浏览器。当用户访问一个被设置为 OutputCache的页面时,ASP.NET在MSIL之后,先将结果写入output cache缓存,然后在发送到浏览器,当用户访问同一路径的页面时,ASP.NET将直接发送被Cache的内容,而不经过.aspx编译以及执行MSIL的过程,所以,虽然程序的本身效率没有提升,但是页面载入速度却得到了提升。
为了实现这个功能,我们继续改写上面的 Application_BeginRequest 事件,我们在 TransmitFile 后,将这个路径的页面以OutputCache编程的方式缓存起来:
Application_BeginRequest( sender, EventArgs e ) { //............. ( DateTime.Now.Subtract( file.LastWriteTime ).TotalMinutes < 5 ) { response.TransmitFile( path ); response.Cache.SetExpires( DateTime.Now.AddMinutes( 5 ) ); response.Cache.SetCacheability( HttpCacheability.Public ); response.End(); ; } //............ }
四、实现CommonFilter类过滤ViewState、过滤NamingContainer、空白字符串,以及生成磁盘的缓存文件
我们传入response.Filter的Stream对象给CommonFilter类:
首先,我们用先Stream的Write方法实现生成磁盘的缓存文件,代码如下,在这些代码中,只有初始化构造函数,Write方法,Close方式是有用的,其中FileStream字段是生成静态文件的操作对象:
ASPNET_CL.Code.HttpModules { CommonFilter : Stream { Stream _responseStream; FileStream _cacheStream; CanRead { get { ; } } CanSeek { get { ; } } CanWrite { get { _responseStream.CanWrite; } } Length { get { NotSupportedException(); } } Position { get { NotSupportedException(); } set { NotSupportedException(); } } CommonFilter( Stream responseStream, FileStream stream ) { _responseStream = responseStream; _cacheStream = stream; } Seek( offset, SeekOrigin origin ) { NotSupportedException(); } SetLength( length ) { NotSupportedException(); } Read( [] buffer, offset, count ) { NotSupportedException(); } Flush() { _responseStream.Flush(); _cacheStream.Flush(); } Write( [] buffer, offset, count ) { _cacheStream.Write( buffer, offset, count ); _responseStream.Write( buffer, offset, count ); } Close() { _responseStream.Close(); _cacheStream.Close(); } Dispose( disposing ) { ( disposing ) { _responseStream.Dispose(); _cacheStream.Dispose(); } } } }
然后我们利用正则完全删除ViewState:
ViewStateFilter( strHTML ) { matchString1 = ; matchString2 = ; matchString3 = ; matchString4 = ; positiveLookahead1 = + Regex.Escape( matchString1 ) + ; positiveLookahead2 = + Regex.Escape( matchString2 ) + ; positiveLookahead3 = + Regex.Escape( matchString3 ) + ; positiveLookahead4 = + Regex.Escape( matchString4 ) + ; RegexOptions opt = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.Compiled; Regex[] arrRe = Regex[] { Regex( + positiveLookahead1 + , opt), Regex( + positiveLookahead2 + , opt), Regex( + positiveLookahead3 + , opt), Regex( + positiveLookahead3 + , opt), Regex( + positiveLookahead4 + , opt) }; ( Regex re arrRe ) { strHTML = re.Replace( strHTML, ); } strHTML; }
以下是删除页面空白的方法:
Regex tabsRe = Regex( , RegexOptions.Compiled | RegexOptions.Multiline ); Regex carriageReturnRe = Regex( , RegexOptions.Compiled | RegexOptions.Multiline ); Regex carriageReturnSafeRe = Regex( , RegexOptions.Compiled | RegexOptions.Multiline ); Regex multipleSpaces = Regex( , RegexOptions.Compiled | RegexOptions.Multiline ); Regex spaceBetweenTags = Regex( , RegexOptions.Compiled | RegexOptions.Multiline ); WhitespaceFilter( html ) { html = tabsRe.Replace( html, .Empty ); html = carriageReturnRe.Replace( html, ); html = carriageReturnSafeRe.Replace( html, ); ( multipleSpaces.IsMatch( html ) ) html = multipleSpaces.Replace( html, ); html = spaceBetweenTags.Replace( html, ); html = html.Replace( , ); html = html.Replace( , ); html; }
以下是删除ASP.NET控件的垃圾UniqueID名称方法:
NamingContainerFilter( html ) { RegexOptions opt = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.Compiled; Regex re = Regex( + Regex.Escape( ) + , opt ); html = re.Replace( html, MatchEvaluator( ( Match m ) { lastDollarSignIndex = m.Value.LastIndexOf( ); ( lastDollarSignIndex >= 0 ) { m.Groups[ 1 ].Value + m.Value.Substring( lastDollarSignIndex + 1 ); } { m.Value; } } ) ); html; }
最后,我们把以上过滤方法整合到CommonFilter类的Write方法:
Write( [] buffer, offset, count ) {
[] data = [ count ];
Buffer.BlockCopy( buffer, offset, data, 0, count );
html = System.Text.Encoding.UTF8.GetString( buffer );
html = NamingContainerFilter( html );
html = ViewStateFilter( html );
html = WhitespaceFilter( html );
[] outdata = System.Text.Encoding.UTF8.GetBytes( html );
_cacheStream.Write( outdata, 0, outdata.GetLength( 0 ) );
_responseStream.Write( outdata, 0, outdata.GetLength( 0 ) );
}
五、缓存破坏
经过以上程序的实现,网页已经被高速缓存在客户端了,如果果用户访问网站被缓存过的页面,则页面会以0请求的速度加载页面。但是,如果后台更新了某些数据,前台用户则不能及时看到最新的数据,因此要改变这种情况,我们必须破坏缓存。根据我们如上的程序,我们破坏缓存只需要做2步:更新服务器上的临时文件,删除OutputCache过的页面。
更新服务器上的文件我们只需删除这个文件即可,当某一用户第一次访问该页面时会自动生成,当然,你也可以用程序先删除后生成:
( var file Directory.GetFiles( HttpRuntime.AppDomainAppPath + ) ) { File.Delete( file ); }
要删除OutputCache关联的缓存项,代码如下,我们只需要保证该方法的参数,指页面的绝对路径是正确的,路径不能使用../这样的相对路径:
HttpResponse.RemoveOutputCacheItem( );
到此,我们实现了针对一个页面的性能,重点是载入速度的提高的一些做法,希望对大家有用~!