栀子花开

追求完美

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




如上图所示,其实程序就是在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
{
    
/// <summary>
    
/// _default 的摘要说明。
    
/// </summary>
    public class _default : BasePage
    {
        
private void Page_Load(object sender, System.EventArgs e)
        {
            
// 在此处放置用户代码以初始化页面
            if(this.CacheProgress())
            {
                
return ;
            }

            initPage();
        }

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

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


/// <summary>
/// 页面的基类
/// Wathon Team.
/// By Json Lee 2007-11-07
/// http://www.wathon.com
/// </summary>
public class BasePage:Page
{
    
/// <summary>
    
/// 自动处理页面缓存
    
/// 当返回true表示要中断页面的所有内容
    
/// false不要做处理
    
/// </summary>
    
/// <returns></returns>
    protected bool CacheProgress()
    {
        
if(Request.QueryString["serverget"== "1")
        {            
            
return false;
        }

        
string strContent  = "";
        
string url = Request.Url.ToString();
        Caches caches 
=  new Caches();

        
if(caches.ExistCache(url))
        {
            
//取缓存
            strContent = caches.GetCache(url);
        }
        
else
        {            
            
//取当前页面的HTML
            strContent = GetUrlResponse(url);            
            
//存缓存
            caches.SetCache(strContent,url);    
        }

        
//输出内容
        Response.Write(strContent);
        Response.End();
        
return true;
    }
    

    
/// <summary>
    
/// 取得URL的页面内容
    
/// </summary>
    
/// <param name="p_PageUrl">URL地址要完整的</param>
    
/// <returns></returns>
    private 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, Encoding.UTF8);

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

        
return strContent;
    }

}


CacheBase.cs (Cache的基类)
using System;
using System.IO;

namespace cacheweb.App_code.FileCache
{
    
/// <summary>
    
/// Cache基类
    
/// 包括了一些常用的方法和配置
    
/// Wathon Team.
    
/// By Json Lee 2007-11-07
    
/// http://www.wathon.com
    
/// </summary>
    public abstract class CacheBase
    {        
        
/// <summary>
        
/// 文件统一的编码格式
        
/// </summary>
        private System.Text.Encoding _FileEncoding = System.Text.Encoding.UTF8;

        
/// <summary>
        
/// Cache文件存放基本目录
        
/// </summary>
        private string _FilePath = @"D:\CacheFiles\Test\";        

        
/// <summary>
        
/// 文件扩展名
        
/// </summary>
        private string _FileExt = ".phtml";

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

        
/// <summary>
        
/// 检查文件是否存在
        
/// </summary>
        
/// <param name="p_FileName">文件名,不带路径,不带扩展名</param>
        
/// <returns></returns>
        protected bool ExistFile(string p_FileName)
        {
            
bool resultValue = false;
            
try
            {
                
string strFileName = _FilePath + 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;
        }

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

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

            
return resultValue;
        }

        
/// <summary>
        
/// 保存文本文件
        
/// </summary>
        
/// <param name="p_FileName">文件名,不带路径,不带扩展名</param>
        
/// <param name="p_Content">内容</param>
        
/// <returns></returns>
        protected bool SaveFile(string p_FileName,string p_Content)
        {
            
bool resultValue = false;
            
try
            {
                System.IO.StreamWriter sw 
= new StreamWriter(_FilePath + p_FileName + _FileExt,false,_FileEncoding);
                sw.Write(p_Content);
                sw.Close();
                resultValue 
= true;
            }
            
catch(Exception ex)
            {
                
throw new Exception(ex.ToString());
            }

            
return resultValue;

        }
    }
}


Cache.cs (Cache类)
using System;

namespace cacheweb.App_code.FileCache
{
    
/// <summary>
    
/// 文件Cache类
    
/// Wathon Team.
    
/// By Json Lee 2007-11-07
    
/// http://www.wathon.com
    
/// </summary>
    public class Caches:CacheBase
    {        
        
        
/// <summary>
        
/// 保存Cache
        
/// </summary>
        
/// <param name="p_Content"></param>
        
/// <param name="p_Url"></param>
        public void SetCache(string p_Content,string p_Url)
        {
            
string fileNameNoExt = GetFileNameNoExt(p_Url);
            
//写在这里            
            this.SaveFile(fileNameNoExt,p_Content);
        }

        
/// <summary>
        
/// 检查Cache文件是否存在或过期
        
/// </summary>
        
/// <param name="p_Url"></param>
        
/// <returns></returns>
        public bool ExistCache(string p_Url)
        {        
            
string fileNameNoExt = GetFileNameNoExt(p_Url);

            
return this.ExistFile(fileNameNoExt);
        }

        
/// <summary>
        
/// 取Cache,请在使用之间先用 ExistCache 确定Cache存在
        
/// </summary>
        
/// <param name="p_Url"></param>
        
/// <returns></returns>
        public string GetCache(string p_Url)
        {
            
string strContent = "";
            
string fileNameNoExt = GetFileNameNoExt(p_Url);
            
this.ReadFile(fileNameNoExt,ref strContent);

            
return strContent;
        }

        
/// <summary>
        
/// 根据域名取得无扩展名的文件名
        
/// </summary>
        
/// <param name="p_Url"></param>
        
/// <returns></returns>
        private string GetFileNameNoExt(string p_Url)
        {
            
string fileNameNoExt = p_Url.Replace("http://","");
            
string fileExt = this.GetExtension(fileNameNoExt);
            fileNameNoExt 
= fileNameNoExt.Replace("/","_").Replace(fileExt,"");
            
//处理未带文件名的情况
            if(fileNameNoExt == "")
            {
                fileNameNoExt 
= "default";
            }
            
return fileNameNoExt;
        }

        
/// <summary>
        
/// 取扩展名
        
/// </summary>
        
/// <param name="fileName"></param>
        
/// <returns></returns>
        private 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;
            }
        }

        
/// <summary>
        
/// 取有扩展名的文件名
        
/// </summary>
        
/// <param name="p_Url"></param>
        
/// <returns></returns>
        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;
            }
        }

    }
}
posted on 2007-11-07 15:52  杨林  阅读(372)  评论(0编辑  收藏  举报