asp.net 自定义文件缓存类

12 篇文章 0 订阅
11 篇文章 0 订阅
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.FileCacheProgress())
            {
                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
{
    #region 缓存
    /// <summary>
    /// 缓存处理
    /// </summary>
    protected bool FileCacheProgress()
    {
        return FileCacheProgress(false, true);
    }

    /// <summary>
    /// 重写缓存
    /// </summary>
    public void FileCacheRewrite()
    {
        FileCacheProgress(true, false);
    }

    /// <summary>
    /// 缓存处理
    /// </summary>
    /// <param name="IsReCache">true强行重写cache</param>
    /// <param name="IsRewritePage">是否重写输入出页面内容</param>
    /// <returns></returns>
    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
{
    /// <summary>
    /// FileCache 文件缓存类 V0.2
    /// Wathon Team
    /// http://www.wathon.com
    /// http://www.cnblogs.com/huacn/archive/2007/11/07/aspnet_page_cache_file.html
    /// </summary>
    public class FileCaches : FileCacheBase
    {
        /// <summary>
        /// 自动处理页面缓存
        /// 当返回true表示要中断页面的所有内容
        /// false不要做处理
        /// 会重Response.Write
        /// </summary>
        /// <param name="httpcontext">请传入当前页的HttpContext</param>
        /// <returns></returns>
        public bool CacheProgress(HttpContext httpcontext)
        {
            return this.CacheProgress(httpcontext, false,true);
        }

        /// <summary>
        /// 自动处理页面缓存
        /// 当返回true表示要中断页面的所有内容
        /// false不要做处理
        /// 会重Response.Write
        /// </summary>
        /// <param name="httpcontent">请传入当前页的HttpContext</param>
        /// <param name="IsReCache">是否强制重写Cahce</param>
        /// <returns></returns>
        public bool CacheProgress(HttpContext httpcontext, bool IsReCache)
        {
            return CacheProgress(httpcontext, IsReCache, true);
        }

        /// <summary>
        /// 自动处理页面缓存
        /// 当返回true表示要中断页面的所有内容
        /// false不要做处理
        /// </summary>
        /// <param name="httpcontent">请传入当前页的HttpContext</param>
        /// <param name="IsReCache">是否强制重写Cahce</param>
        /// <param name="IsRewritePage">是否重写页面内容 Response.Write 当为False时,只是重新生成静态文件,页面内容不会变动</param>
        /// <returns></returns>
        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<!-- FileCache By " + DateTime.Now.ToUniversalTime() + " -->";
                //存缓存
                this.SetCache(strContent, strUrl, strDomain);
            }
            else
            {

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


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




        /// <summary>
        /// 保存Cache
        /// </summary>
        /// <param name="p_Content"></param>
        /// <param name="p_Url">页面地址</param>
        /// <param name="p_Domain">域名</param>
        public void SetCache(string p_Content, string p_Url,string p_Domain)
        {
            string fileNameNoExt = GetFileNameNoExt(p_Url, p_Domain);
            //写在这里            
            this.SaveFile(fileNameNoExt, p_Content);
        }

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

            return this.ExistFile(fileNameNoExt);
        }

        /// <summary>
        /// 取Cache,请在使用之间先用 ExistCache 确定Cache存在
        /// </summary>
        /// <param name="p_Url">页面地址</param>
        /// <param name="p_Domain">域名</param>
        /// <returns></returns>
        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;
        }
    }

    /// <summary>
    /// 文件缓存基类
    /// By Json Lee 2007-11-07
    /// </summary>
    public abstract class FileCacheBase 
    {
        #region 属性定义
        /// <summary>
        /// 文件统一的编码格式
        /// </summary>
        private System.Text.Encoding _FileEncoding = System.Text.Encoding.UTF8;
        /// <summary>
        /// 文件统一的编码格式
        /// </summary>
        public System.Text.Encoding FileEncoding
        {
            get { return _FileEncoding; }
            set { _FileEncoding = value; }
        }


        /// <summary>
        /// Cache文件存放基本目录
        /// </summary>
        private string _FileSavePath = @"c:\CacheFiles\";
        /// <summary>
        /// Cache文件存放基本目录
        /// </summary>
        public string FileSavePath
        {
            get { return _FileSavePath; }
            set { _FileSavePath = value; }
        }

        /// <summary>
        /// 文件扩展名
        /// </summary>
        private string _FileExt = ".cache";
        /// <summary>
        /// Cache文件扩展名
        /// </summary>
        public string FileExt
        {
            set { _FileExt = value; }
            get { return _FileExt; }
        }

        /// <summary>
        /// 文件缓存的时间 单位分
        /// </summary>
        private int _FileCacheMiniutes = 2;
        /// <summary>
        /// 文件缓存的时间 单位分
        /// </summary>
        public int FileCacheMiniutes
        {
            get { return _FileCacheMiniutes; }
            set { _FileCacheMiniutes = value; }
        }
        #endregion

        /// <summary>
        /// 检查文件是否存在
        /// </summary>
        /// <param name="p_FileName">文件名,不带路径,不带扩展名</param>
        /// <returns></returns>
        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;
        }

        /// <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
            {
                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;
        }

        /// <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
            {
                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;

        }


        /// <summary>
        /// 根据域名取得无扩展名的文件名
        /// </summary>
        /// <param name="p_Url"></param>
        /// <param name="p_Domain">域名</param>
        /// <returns></returns>
        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;
        }

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

        /// <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;
            }
        }


        /// <summary>
        /// 取得URL的页面内容
        /// </summary>
        /// <param name="p_PageUrl">URL地址要完整的</param>
        /// <returns></returns>
        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 格式化文件名,替换非法字符
        /// <summary>
        /// 格式化文件名,替换非法字符
        /// </summary>
        /// <param name="p_fileName">需要格式化的文件名</param>
        /// <returns>格式化后的文件名</returns>
        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

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值