asp.net中缓存类DataCache(依赖文件缓存和时间缓存,或两者)

更新:2013-12-29

经过不断的修改和运行测试,在实际项目中使用得很好的了。。

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.IO;

namespace Tools.Web
{
    /// <summary>
    /// 网页中的缓存类,使用示例:
    /// object obj = DataCache.GetCache("file1",depfile);
    ///if (obj == null)
    ///{
    ///   string txt = "缓存内容";//从数据库或文件读取到的内容
    ///   DataCache.SetCacheDepFile("file1", txt, depfile);
    /// }
    /// else
    /// {
    ///     string txt=obj.ToString();
    /// }
    /// </summary>
    public partial class DataCache
    {
        #region 文件路径web.config
        private static string _webconfigfile = string.Empty;
        /// <summary>
        /// 文件路径web.config
        /// </summary>
        public static string webconfigfile
        {
            get
            {
                if (string.IsNullOrEmpty(_webconfigfile)) _webconfigfile = HttpContext.Current.Server.MapPath("/web.config");
                return _webconfigfile;
            }
        }
        #endregion

        #region 文件路径App_Data/ShopConfig.config
        private static string _shopconfigfile = string.Empty;
        /// <summary>
        /// 文件路径App_Data/ShopConfig.config
        /// </summary>
        public static string shopconfigfile
        {
            get
            {
                if (string.IsNullOrEmpty(_shopconfigfile)) _shopconfigfile = HttpContext.Current.Server.MapPath("/App_Data/ShopConfig.config");
                return _shopconfigfile;
            }
        }
        #endregion

        #region 文件路径App_Data/SiteConfig.config
        private static string _siteconfigfile = string.Empty;
        /// <summary>
        /// 文件路径App_Data/SiteConfig.config
        /// </summary>
        public static string siteconfigfile
        {
            get
            {
                if (string.IsNullOrEmpty(_siteconfigfile)) _siteconfigfile = HttpContext.Current.Server.MapPath("/App_Data/SiteConfig.config");
                return _siteconfigfile;
            }
        }
        #endregion

        #region 文件路径App_Data/Template.config
        private static string _templateconfigfile = string.Empty;
        /// <summary>
        /// 文件路径App_Data/Template.config
        /// </summary>
        public static string templateconfigfile
        {
            get
            {
                if (string.IsNullOrEmpty(_templateconfigfile)) _templateconfigfile = HttpContext.Current.Server.MapPath("/App_Data/Template.config");
                return _templateconfigfile;
            }
        }
        #endregion

        #region 删除缓存
        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="CacheKey">键</param>
        public static void DeleteCache(string CacheKey)
        {
            HttpRuntime.Cache.Remove(CacheKey);
        }
        #endregion

        #region 获取缓存,依赖时间
        /// <summary>
        /// 获取缓存,依赖时间
        /// </summary>
        /// <param name="CacheKey">键</param>
        /// <returns></returns>
        public static object GetCache(string CacheKey)
        {
            object obj_time=HttpRuntime.Cache[CacheKey + "_time"];
            object obj_cache=HttpRuntime.Cache[CacheKey];
            if (obj_time != null && obj_cache!=null)
            {
                if (Convert.ToDateTime(obj_time) < DateTime.Now)
                {
                    DeleteCache(CacheKey);
                    DeleteCache(CacheKey + "_time");
                    return null;
                }
                else return obj_cache;
            }
            else
            {
                DeleteCache(CacheKey);
                DeleteCache(CacheKey+"_time");
                return null;
            }
        }
        #endregion

        #region 获取缓存,依赖文件
        /// <summary>
        /// 获取缓存,依赖文件
        /// </summary>
        /// <param name="CacheKey">键</param>
        /// <param name="depFile">依赖的文件</param>
        /// <returns></returns>
        public static object GetCache(string CacheKey, string depFile)
        {
            object obj_time = HttpRuntime.Cache[CacheKey + "_time"];
            object obj_cache = HttpRuntime.Cache[CacheKey];
            if (File.Exists(depFile))
            {
                FileInfo fi = new FileInfo(depFile);

                if (obj_time != null && obj_cache != null)
                {
                    if (Convert.ToDateTime(obj_time) != fi.LastWriteTime)
                    {
                        DeleteCache(CacheKey);
                        DeleteCache(CacheKey + "_time");
                        return null;
                    }
                    else return obj_cache;
                }
                else
                {
                    DeleteCache(CacheKey);
                    DeleteCache(CacheKey + "_time");
                    return null;
                }
            }
            else
            {
                throw new Exception("文件(" + depFile + ")不存在!");
            }
        }
        #endregion

        #region 简单的插入缓存
        /// <summary>
        /// 简单的插入缓存
        /// </summary>
        /// <param name="CacheKey">键</param>
        /// <param name="objObject">数据</param>
        public static void SetCache(string CacheKey, object objObject)
        {
            HttpRuntime.Cache.Insert(CacheKey, objObject);
        }
        #endregion

        #region 有过期时间的插入缓存数据
        /// <summary>
        /// 有过期时间的插入缓存数据
        /// </summary>
        /// <param name="CacheKey">键</param>
        /// <param name="objObject">数据</param>
        /// <param name="absoluteExpiration">过期时间</param>
        /// <param name="slidingExpiration">可调度参数,传null就是禁用可调度</param>
        public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            if (slidingExpiration == null) slidingExpiration = Cache.NoSlidingExpiration;
            HttpRuntime.Cache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);
            HttpRuntime.Cache.Insert(CacheKey + "_time", absoluteExpiration, null, absoluteExpiration, slidingExpiration);//存储过期时间
        }
        #endregion

        #region 插入缓存数据,指定缓存多少秒
        /// <summary>
        /// 插入缓存数据,指定缓存多少秒
        /// </summary>
        /// <param name="CacheKey">缓存的键</param>
        /// <param name="objObject">缓存的数据</param>
        /// <param name="seconds">缓存秒数</param>
        /// <param name="slidingExpiration">传null就是禁用可调度过期</param>
        public static void SetCacheSecond(string CacheKey, object objObject, int seconds, TimeSpan slidingExpiration)
        {
            DateTime absoluteExpiration = DateTime.Now.AddSeconds(seconds);
            if (slidingExpiration == null) slidingExpiration = Cache.NoSlidingExpiration;
            HttpRuntime.Cache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);
            HttpRuntime.Cache.Insert(CacheKey + "_time", absoluteExpiration, null, absoluteExpiration, slidingExpiration);//存储过期时间
        }
        #endregion

        #region 依赖文件的缓存,文件没改不会过期
        /// <summary>
        /// 依赖文件的缓存,文件没改不会过期
        /// </summary>
        /// <param name="CacheKey">键</param>
        /// <param name="objObject">数据</param>
        /// <param name="depfilename">依赖文件,可调用 DataCache 里的变量</param>
        public static void SetCacheDepFile(string CacheKey, object objObject, string depfilename)
        {
            //缓存依赖对象
            System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency(depfilename);
            DateTime absoluteExpiration = System.Web.Caching.Cache.NoAbsoluteExpiration;
            TimeSpan slidingExpiration=System.Web.Caching.Cache.NoSlidingExpiration;
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(
                CacheKey,
                objObject,
                dep,
                System.Web.Caching.Cache.NoAbsoluteExpiration, //从不过期
                slidingExpiration, //禁用可调过期
                System.Web.Caching.CacheItemPriority.Default,
                null);
            if (File.Exists(depfilename))
            {
                FileInfo fi = new FileInfo(depfilename);
                DateTime lastWriteTime = fi.LastWriteTime;
                HttpRuntime.Cache.Insert(CacheKey + "_time", lastWriteTime, null, absoluteExpiration, slidingExpiration);//存储文件最后修改时间
            }

        }
        #endregion
    }
}
时间: 2024-07-29 22:15:16

asp.net中缓存类DataCache(依赖文件缓存和时间缓存,或两者)的相关文章

ASP.NET中通过对话框方式下载文件

ASP.NET中通过对话框方式下载文件 1 通过探出对话框提示文件下载或打开 2 通过自定义Header让特定的应用程序打开文件  使用的方法:Response.TransmitFile()  例程: Response.ContentType = "image/jpeg";Response.AppendHeader("Content-Disposition","attachment; filename=SailBig.jpg");Response

在asp.net中如何上传大文件

在asp.net中如何上传大文件呢?我们需要配置Web.config文件.具体如下: 在web.config中的<system.web></system.web>内加入如下代码: <httpRuntime executi maxRequestLength="951200" useFullyQualifiedRedirectUrl="true" minFreeThreads="8" minLocalRequestFre

为什么在asp.net中删除新建好的文件夹,在新建文件夹图片不可以粘贴

问题描述 为什么在ASP.NET中添加文件夹存放图片,本来复制图片,粘贴可以,但是删除文件夹,在新建文件夹,复制图片,不可以粘贴 解决方案 解决方案二:不会的,你确认复制粘贴了?解决方案三:重启你的计算机.解决方案四:可以复制的啊,你是怎么复制粘贴的

ASP.NET中单态类的方法并发访问的会有问题么?

问题描述 ImportsSystem.Data.OleDbPublicClassTestModulePrivateSharedunlockMLAsTestModule=NothingPrivateSharedReadOnlyobjAsObject=NewObjectPublicSharedFunctionGetInstance()AsTestModuleSyncLockobjIfunlockMLIsNothingThenunlockML=NewTestModuleEndIfReturnunloc

在ASP.NET中支持断点续传下载大文件(ZT)源码_实用技巧

IE的自带下载功能中没有断点续传功能,要实现断点续传功能,需要用到HTTP协议中鲜为人知的几个响应头和请求头. 一. 两个必要响应头Accept-Ranges.ETag 客户端每次提交下载请求时,服务端都要添加这两个响应头,以保证客户端和服务端将此下载识别为可以断点续传的下载: Accept-Ranges:告知下载客户端这是一个可以恢复续传的下载,存放本次下载的开始字节位置.文件的字节大小: ETag:保存文件的唯一标识(我在用的文件名+文件最后修改时间,以便续传请求时对文件进行验证): Las

linux中如何使用touch修改文件的修改时间

rsync有时候因为服务器时间错了,需要更改文件的修改时间时间,可以使用 touch命令来修改文件的修改时间: 1 touch -c -m -t 201101110000 teadme.txt 修改readme.txt为2011年1月11日零时零分修改 如果批量修改文件和目录,则使用 1 find /home/www/site -exec touch -c -m -t 201101110000 {} \; 即可把/home/www/site下的所有文件和目录都改变修改时间. 注意上面命令中的空格

ASP.NET中基类Page_Load方法后执行的原因

加载对应Load事件和OnLoad方法,对于这个事件,相信大多数朋友都会比较熟悉,用VS.Net生成的页面中的Page_Load方法就是响应Load事件的方法,对于每一次请求,Load事件都会触发,Page_Load方法也就会执行,相信这也是大多数人了解ASP.Net的第一步. Page_Load方法响应了Load事件,这个事件是在System.Web.WebControl.Control类中定义的(这个类是Page和所有服务器控件的祖宗),并且在OnLoad方法中被触发. 很多人可能碰到过这样

ASP.NET中基类页的设计和使用

在Asp.net业务系统的开发过程中,为了保证页面风格的一致性以及减少重复代码的编写,我们需要引入基类页的概念,即:定义一个基类页,让所有的页面都继承这个基类,并在该基类页中加入公用的属性和方法. 实际使用时,按照功能页面划分,可以定义多个基类页,如: class FormBase class BizFormBase :FormBase class ViewFormBase : BizFormBase class EditFormBase : BizFormBase class QueryFor

asp.net中SQLHelper类实现数据库操作

自己的DBHelper类 显示代码  代码如下 复制代码  public class DBHelper      {          /// <summary>          /// 从Web.config配置文件中读取数据库连接          /// </summary>          private static string connectionStrings = ConfigurationManager.ConnectionStrings["MyCo