`
hugh-lin
  • 浏览: 70621 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

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

阅读更多
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(falsetrue);
    }

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

    
/// <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)
          &nbs
分享到:
评论

相关推荐

    分布式缓存系统Memcached

     Memcached是高性能的,分布式的内存对象缓存系统,用于在动态应用中减少数据库负载,提升访问速度。Memcached通过在内存里维护一个统一的巨大的hash表,它能够用来存储各种格式的数据,包括图像、视频、文件以及...

    Windows 11垃圾文件清理

    Windows 11清除无效、垃圾、过期、缓存、补丁更新文件。还电脑一个更加干净的环境,减少负载,跑的更快。

    Fikker设计与实现V3

    Fikker 是一款面向广大站长的专业级网站加速服务器软件,跨平台,全界面化管理,利用页面缓存技术(webcache),网站管理员或开发人员通过 Fikker 管理平台将指定的页面缓存起来,其他用户在访问相同页面时候,就不...

    网站架构技术

    使用缓存改善网站性能 缓存类型 本地缓存 分布式缓存 缓存产品 redis 业界主流 memcached 解决问题 数据库访问 使用应用服务器集群改善网站的并发处理能力 问题: 负载均衡...

    HTML5 应用程序缓存

    HTML5 应用程序缓存 使用 HTML5,通过创建 cache manifest 文件,...减少服务器负载 – 浏览器将只从服务器下载更新过或更改过的资源。 浏览器支持 Internet Explorer 10, Firefox, Chrome, Safari 和 Opera 支持

    构建高性能Web站点_PDF_45.5M

    7.3 缓存文件描述符 第8章 反向代理缓存 8.1 传统代理 8.2 何为反向 8.3 在反向代理上创建缓存 8.4 小心穿过代理 8.5 流量分配 第9章 Web组件分离 9.1 备受争议的分离 9.2 因材施教 9.3 拥有不同的域名 ...

    构建高性能Web站点(PDF)

    7.3 缓存文件描述符 第8章 反向代理缓存 8.1 传统代理 8.2 何为反向 8.3 在反向代理上创建缓存 8.4 小心穿过代理 8.5 流量分配 第9章 Web组件分离 9.1 备受争议的分离 9.2 因材施教 9.3 拥有不同的域名 ...

    构建高性能Web站点(PDF)-第2部分

    7.3 缓存文件描述符 第8章 反向代理缓存 8.1 传统代理 8.2 何为反向 8.3 在反向代理上创建缓存 8.4 小心穿过代理 8.5 流量分配 第9章 Web组件分离 9.1 备受争议的分离 9.2 因材施教 9.3 拥有不同的域名 ...

    PHP缓存库phpFastCache.zip

    phpfastcache是一种高性能,分布式对象缓存系统,通用性,可用于加快动态Web应用程序,减轻数据库负载。 phpfastcache把数据库负载到几乎为零,得到更快的页面加载时间的用户,更好的资源利用率。它是简单而强大的...

    engintron:Engintron for cPanelWHM是将Nginx集成到cPanelWHM服务器上的最简单方法。 通过安装和配置流行的Nginx Web服务器以充当Apache前面的反向缓存代理,Engintron将提高服务器的性能和Web服务容量,同时减少CPURAM负载

    它通过安装和配置流行的Nginx Web服务器来充当静态文件(如CSS,JS,图像等)的反向缓存代理,并带有附加的微缓存层来实现此目的,从而显着提高WordPress等CMS生成的动态内容的性能,Joomla或Drupal以及论坛软件...

    codeIgniter-multi-level-cache:简单的修改即可将缓存文件存储到多级子文件夹中

    Codeigniter的基于文件的缓存系统将完全呈现HTML和SQL对象的输出,当用户访问您的网页时,Codeigniter将从没有MySQL连接的缓存文件中加载数据,这大大减少了服务器CPU的负载。 但是,如果同一文件夹中有100K缓存...

    WJCMS网站管理系统 v1.2.rar

    高效缓存机制 数据负载能力显赫 快速模块开发 3分钟可自定义内容模块 内含电影,文章,音乐内容模块。满足多媒体行业门户网站需求 模板制作简易.数据随意调取 1.2较于1.1: 添加了 视频和图片模块。 ...

    基于SpringBoot框架搭建的物联网数据采集系统服务器端(源码)

    框架SpringBoot+MyBatis,相比于SSM版的项目大大减少了xml配置,仅在application.yml文件中配置了少量信息 * 2.添加Redis缓存,在以下部分提供缓存支持: * 当查询单个Gateway、Sensor、SensorClassify时使用查询...

    架构设计方案

    2)页面尽可能静态化以减少动态数据访问,如果是资讯类的网站可以考虑采用第三方开源的CMS系统来生成静态的内容页面。 3)采用Oscache实现页面缓存,采用Memcached实现数据缓存 4)采用独立的图片服务器集群来实现图片...

    最全面的门户网站架构设计方案.doc

    2.1.2 WEB应用开发架构思路 1) 应用开发实现MVC架构三层架构进行web应用开发 2) 页面尽可能静态化以减少动态数据访问,如果是资讯类的网站可以考虑采用第三 方开源的CMS系统来生成静态的内容页面。 3) 采用Oscache...

    memcached安装文件和安装使用说明

    它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提供动态、数据库驱动网站的速度。Memcached基于一个存储键/值对的hashmap。其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过...

    搭建nginx点播服务器

    通过缓存,它可以减少对源服务器的请求,从而减轻服务器负担。 安全性:Nginx支持HTTPS,可以加密点播内容的传输,保护用户隐私和数据安全。 负载均衡:如果需要,Nginx可以配置为分发点播内容的负载均衡,确保请求...

    Web应用项目的优化()

    前端优化是Web应用开发的重点之一,通过减小页面请求量、压缩和合并JS和CSS文件、优化图片大小和清晰度等方式来减少页面加载时间和提高用户体验。同时,可以使用浏览器缓存技术来减少页面请求次数,从而提高页面响应...

    memcached-win32-1.4.4-14内存数据库

    它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态、数据库驱动网站的速度。Memcached基于一个存储键/值对的hashmap。其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过...

Global site tag (gtag.js) - Google Analytics