[转]文件缓存的方式减少网站负载

Asp.net 缓存Cache功能已经是很常见的功能了,网络上面这种相关的文章也非常之多,我这里所要讲的缓存并不是.NET所提供的缓存,而是过通文件方式来存放的。这样可以很好的减少服务器资源。
先看一下我做这个的缓存流程图:


[转]文件缓存的方式减少网站负载_第1张图片

如上图所示,其实程序就是在Page_Load的时候做一下判断,是否有缓存文件存在或者缓存是否过期(过期的判断是通过文件的最后修改日期来处理的),如果没有,它将会去读取当前页的页面HTML代码,并用当前页的文件名保存成一个文件缓存。下次再打开此页的时候就会去读取存下来的缓存文件的内容,并同时中断PageLoad后边的方式,从页实现很有效的使用很方便的缓存机制。

以下是部分代码
default.aspx.cs (一个普通的服务端页面)
using  System;
using  System.Collections;
using  System.ComponentModel;
using  System.Data;
using  System.Drawing;
using  System.Web;
using  System.Web.SessionState;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.HtmlControls;

namespace  cacheweb
{
    
///  
    
///  _default 的摘要说明。
    
///  

     public   class  _default : BasePage
    {
        
private   void  Page_Load( object  sender, System.EventArgs e)
        {
            
//  在此处放置用户代码以初始化页面
             if ( this .FileCacheProgress())
            {
                
return  ;
            }

            initPage();
        }

        
private   void  initPage()
        {            
            Response.Write(
" FileCache V0.1 - 文件缓存方式的功能演示 " );
            Response.Write(
" Wathon Team " );
            Response.Write(
" " http: // www.wathon.com\"> http://www.wathon.com ");
            Response.Write( " " http: // www.cnblogs.com/huacn/archive/2007/11/07/aspnet_page_cache_file.html\">参数讨论");
            Response.Write( " 以下是上次缓存的时间: " );
            Response.Write(DateTime.Now.ToLocalTime()
+ " " );
            Response.Write(DateTime.Now.ToLongDateString()
+ " " );
            Response.Write(DateTime.Now.ToLongTimeString()
+ " " );
            Response.Write(DateTime.Now.ToOADate()
+ " " );
            Response.Write(DateTime.Now.ToShortDateString()
+ " " );
            Response.Write(DateTime.Now.ToUniversalTime()
+ " " );
            Response.Write(DateTime.Now.ToShortTimeString()
+ " " );
        }

        
#region  Web 窗体设计器生成的代码
        
override   protected   void  OnInit(EventArgs e)
        {
            
//
            
//  CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
            
//
            InitializeComponent();
            
base .OnInit(e);
        }
        
        
///  
        
///  设计器支持所需的方法 - 不要使用代码编辑器修改
        
///  此方法的内容。
        
///  

         private   void  InitializeComponent()
        {    
            
this .Load  +=   new  System.EventHandler( this .Page_Load);
        }
        
#endregion
    }
}


BasePage.cs (页面的基类)
using  System;
using  System.Web;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Net;
using  System.Text;
using  System.IO;
using  cacheweb.App_code.FileCache;


///  
///  页面的基类
///  Wathon Team.
///  By Json Lee 2007-11-07
///   http://www.wathon.com
///  

public   class  BasePage:Page
{
    
#region  缓存
    
///  
    
///  缓存处理
    
///  

     protected   bool  FileCacheProgress()
    {
        
return  FileCacheProgress( false true );
    }

    
///  
    
///  重写缓存
    
///  

     public   void  FileCacheRewrite()
    {
        FileCacheProgress(
true false );
    }

    
///  
    
///  缓存处理
    
///  

    
///   true强行重写cache
    
///   是否重写输入出页面内容
    
///  
     private   bool  FileCacheProgress( bool  IsReCache, bool  IsRewritePage)
    {
        FileCaches filecaches 
=   new  FileCaches();
        
try
        {
            filecaches.FileCacheMiniutes 
=   30 ;
            filecaches.FileExt 
=   " .cache " ;
            filecaches.FileSavePath 
=   @" D:\CacheFiles\Test " ;

            
if  (filecaches.CacheProgress(HttpContext.Current, IsReCache, IsRewritePage))
            {
                
return   true ;
            }
        }
        
catch  (Exception ex)
        {
            
throw   new  Exception(ex.ToString());
        }

        
return   false ;
    }
    
#endregion

}


FileCaches.cs (Cache主要类)
using  System;
using  System.Web;
using  System.Text;
using  System.IO;
using  System.Net;

namespace  cacheweb.App_code.FileCache
{
    
///  
    
///  FileCache 文件缓存类 V0.2
    
///  Wathon Team
    
///   http://www.wathon.com
    
///   http://www.cnblogs.com/huacn/archive/2007/11/07/aspnet_page_cache_file.html
    
///  

     public   class  FileCaches : FileCacheBase
    {
        
///  
        
///  自动处理页面缓存
        
///  当返回true表示要中断页面的所有内容
        
///  false不要做处理
        
///  会重Response.Write
        
///  

        
///   请传入当前页的HttpContext
        
///  
         public   bool  CacheProgress(HttpContext httpcontext)
        {
            
return   this .CacheProgress(httpcontext,  false , true );
        }

        
///  
        
///  自动处理页面缓存
        
///  当返回true表示要中断页面的所有内容
        
///  false不要做处理
        
///  会重Response.Write
        
///  

        
///   请传入当前页的HttpContext
        
///   是否强制重写Cahce
        
///  
         public   bool  CacheProgress(HttpContext httpcontext,  bool  IsReCache)
        {
            
return  CacheProgress(httpcontext, IsReCache,  true );
        }

        
///  
        
///  自动处理页面缓存
        
///  当返回true表示要中断页面的所有内容
        
///  false不要做处理
        
///  

        
///   请传入当前页的HttpContext
        
///   是否强制重写Cahce
        
///   是否重写页面内容 Response.Write 当为False时,只是重新生成静态文件,页面内容不会变动
        
///  
         public   bool  CacheProgress(HttpContext httpcontext, bool  IsReCache, bool  IsRewritePage)
        {
            
if  (httpcontext.Request.QueryString[ " serverget " ==   " 1 " )
            {
                
return   false ;
            }

            
string  strContent  =   "" ;
            
string  strUrl  =  httpcontext.Request.Url.ToString();
            
string  strDomain  =  httpcontext.Request.Url.Host;

            
if  ( this .ExistCache(strUrl, strDomain)  ==   false   ||  IsReCache  ==   true )
            {
                
// 取当前页面的HTML
                strContent  =   this .GetUrlResponse(strUrl);
                strContent 
+=   " \r\n " ;
                
// 存缓存
                 this .SetCache(strContent, strUrl, strDomain);
            }
            
else
            {

                
// 取缓存
                strContent  =   this .GetCache(strUrl, strDomain);
            }


            
// 输出内容,当是重写Cache
             if  (IsRewritePage)
            {
                httpcontext.Response.Write(strContent);
                httpcontext.Response.End();
            }
            
            
return   true ;
        }




        
///  
        
///  保存Cache
        
///  

        
///  
        
///   页面地址
        
///   域名
         public   void  SetCache( string  p_Content,  string  p_Url, string  p_Domain)
        {
            
string  fileNameNoExt  =  GetFileNameNoExt(p_Url, p_Domain);
            
// 写在这里            
             this .SaveFile(fileNameNoExt, p_Content);
        }

        
///  
        
///  检查Cache文件是否存在或过期
        
///  

        
///   页面地址
        
///   域名
        
///  
         public   bool  ExistCache( string  p_Url, string  p_Domain)
        {
            
string  fileNameNoExt  =  GetFileNameNoExt(p_Url,p_Domain);

            
return   this .ExistFile(fileNameNoExt);
        }

        
///  
        
///  取Cache,请在使用之间先用 ExistCache 确定Cache存在
        
///  

        
///   页面地址
        
///   域名
        
///  
         public   string  GetCache( string  p_Url,  string  p_Domain)
        {
            
string  strContent  =   "" ;
            
string  fileNameNoExt  =  GetFileNameNoExt(p_Url, p_Domain);
            
this .ReadFile(fileNameNoExt,  ref  strContent);

            
return  strContent;
        }
    }

    
///  
    
///  文件缓存基类
    
///  By Json Lee 2007-11-07
    
///  

     public   abstract   class  FileCacheBase 
    {
        
#region  属性定义
        
///  
        
///  文件统一的编码格式
        
///  

         private  System.Text.Encoding _FileEncoding  =  System.Text.Encoding.UTF8;
        
///  
        
///  文件统一的编码格式
        
///  

         public  System.Text.Encoding FileEncoding
        {
            
get  {  return  _FileEncoding; }
            
set  { _FileEncoding  =  value; }
        }


        
///  
        
///  Cache文件存放基本目录
        
///  

         private   string  _FileSavePath  =   @" c:\CacheFiles\ " ;
        
///  
        
///  Cache文件存放基本目录
        
///  

         public   string  FileSavePath
        {
            
get  {  return  _FileSavePath; }
            
set  { _FileSavePath  =  value; }
        }

        
///  
        
///  文件扩展名
        
///  

         private   string  _FileExt  =   " .cache " ;
        
///  
        
///  Cache文件扩展名
        
///  

         public   string  FileExt
        {
            
set  { _FileExt  =  value; }
            
get  {  return  _FileExt; }
        }

        
///  
        
///  文件缓存的时间 单位分
        
///  

         private   int  _FileCacheMiniutes  =   2 ;
        
///  
        
///  文件缓存的时间 单位分
        
///  

         public   int  FileCacheMiniutes
        {
            
get  {  return  _FileCacheMiniutes; }
            
set  { _FileCacheMiniutes  =  value; }
        }
        
#endregion

        
///  
        
///  检查文件是否存在
        
///  

        
///   文件名,不带路径,不带扩展名
        
///  
         protected   bool  ExistFile( string  p_FileName)
        {
            
bool  resultValue  =   false ;
            
try
            {
                
string  strFileName  =  _FileSavePath  +  p_FileName  +  _FileExt;
                
if  (File.Exists(strFileName))
                {
                    
// 文件是否过期
                    DateTime tmFile  =  File.GetLastWriteTime(strFileName);
                    DateTime tmNow 
=  DateTime.Now;
                    TimeSpan ts 
=  tmNow  -  tmFile;
                    
if  (ts.TotalMinutes  <  _FileCacheMiniutes)
                    {
                        resultValue 
=   true ;
                    }
                }

            }
            
catch  (Exception ex)
            {
                
throw   new  Exception(ex.ToString());
            }

            
return  resultValue;
        }

        
///  
        
///  读文本文件
        
///  

        
///   文件名,不带路径,不带扩展名
        
///   返回用于存放内容的变量
        
///  
         protected   bool  ReadFile( string  p_FileName,  ref   string  p_Content)
        {
            
bool  resultValue  =   false ;
            
if  ( ! this .ExistFile(p_FileName))
            {
                
return  resultValue;
            }


            
try
            {
                
if  ( ! Directory.Exists(_FileSavePath))
                {
                    Directory.CreateDirectory(_FileSavePath);
                }

                System.IO.StreamReader sr 
=   new  StreamReader(_FileSavePath  +  p_FileName  +  _FileExt, _FileEncoding);
                p_Content 
=  sr.ReadToEnd();
                sr.Close();
                resultValue 
=   true ;
            }
            
catch  (Exception ex)
            {
                
throw   new  Exception(ex.ToString());
            }

            
return  resultValue;
        }

        
///  
        
///  保存文本文件
        
///  

        
///   文件名,不带路径,不带扩展名
        
///   内容
        
///  
         protected   bool  SaveFile( string  p_FileName,  string  p_Content)
        {
            
bool  resultValue  =   false ;
            
try
            {
                
if  ( ! Directory.Exists(_FileSavePath))
                {
                    Directory.CreateDirectory(_FileSavePath);
                }

                System.IO.StreamWriter sw 
=   new  StreamWriter(_FileSavePath  +  p_FileName  +  _FileExt,  false , _FileEncoding);
                sw.Write(p_Content);
                sw.Close();
                resultValue 
=   true ;
            }
            
catch  (Exception ex)
            {
                
throw   new  Exception(ex.ToString());
            }

            
return  resultValue;

        }


        
///  
        
///  根据域名取得无扩展名的文件名
        
///  

        
///  
        
///   域名
        
///  
         protected   string  GetFileNameNoExt( string  p_Url, string  p_Domain)
        {
            
string  fileNameNoExt  =  p_Url.Replace( " http:// " + p_Domain + " / " "" );
            fileNameNoExt 
=  FormatFilename(fileNameNoExt);
            
// 处理未带文件名的情况
             if  (fileNameNoExt  ==   "" )
            {
                fileNameNoExt 
=   " default " ;
            }
            
return  fileNameNoExt;
        }

        
///  
        
///  取扩展名
        
///  

        
///  
        
///  
         protected   string  GetExtension( string  fileName)
        {
            
try
            {
                
int  startPos  =  fileName.LastIndexOf( " . " );
                
string  ext  =  fileName.Substring(startPos, fileName.Length  -  startPos);
                
return  ext.ToLower();
            }
            
catch  (Exception ex)
            {
                
// WrongLog.WriteErrorLog(ex.ToString());
                 return   string .Empty;
            }
        }

        
///  
        
///  取有扩展名的文件名
        
///  

        
///  
        
///  
         protected   string  GetFileName( string  p_Url)
        {
            
try
            {
                
int  startPos  =  p_Url.LastIndexOf( " / " +   1 ;
                
string  tmpFileName  =  p_Url.Substring(startPos, p_Url.Length  -  startPos);
                
return  tmpFileName;
            }
            
catch  (Exception ex)
            {
                
// WrongLog.WriteErrorLog(ex.ToString());
                 return   string .Empty;
            }
        }


        
///  
        
///  取得URL的页面内容
        
///  

        
///   URL地址要完整的
        
///  
         protected   string  GetUrlResponse( string  p_PageUrl)
        {
            
// 给URL加入ServerGet的参数,以防止重复循环
             if  (p_PageUrl.IndexOf( " ? " >   0 )
            {
                p_PageUrl 
+=   " &serverget=1 " ;
            }
            
else
            {
                p_PageUrl 
+=   " ?serverget=1 " ;
            }

            WebRequest webrequest 
=  WebRequest.Create(p_PageUrl);
            
string  strContent  =   "" ;
            
try
            {
                WebResponse webresponse 
=  webrequest.GetResponse();
                Stream stream 
=  webresponse.GetResponseStream();
                StreamReader sr 
=   new  StreamReader(stream, _FileEncoding);

                strContent 
=  sr.ReadToEnd();
            }
            
catch  (Exception ex)
            {
                
throw   new  Exception(ex.ToString());
            }

            
return  strContent;
        }

        
#region  格式化文件名,替换非法字符
        
///  
        
///  格式化文件名,替换非法字符
        
///  

        
///   需要格式化的文件名
        
///   格式化后的文件名
         protected   static   string  FormatFilename( string  p_fileName)
        {
            p_fileName 
=  p_fileName.Replace( " \\ " " _ " );
            p_fileName 
=  p_fileName.Replace( " / " " _ " );
            p_fileName 
=  p_fileName.Replace( " : " " _ " );
            p_fileName 
=  p_fileName.Replace( " * " " _ " );
            p_fileName 
=  p_fileName.Replace( " ? " " _ " );
            p_fileName 
=  p_fileName.Replace( " \ "" " _ " );
            p_fileName  =  p_fileName.Replace( " < " " _ " );
            p_fileName 
=  p_fileName.Replace( " > " " _ " );
            p_fileName 
=  p_fileName.Replace( " | " " _ " );
            p_fileName 
=  p_fileName.Replace( " + " " _ " );
            
return  p_fileName.ToLower();
        }
        
#endregion

    }
}

转载于:https://www.cnblogs.com/hugh-lin/archive/2007/11/07/952336.html

你可能感兴趣的:([转]文件缓存的方式减少网站负载)