System.Web.Caching 命名空间提供用于缓存服务器上常用数据的类。此命名空间包括 Cache 类,该类是一个字典,您可以在其中存储任意数据对象,如哈希表和数据集。它还为这些对象提供了失效功能,并为您提供了添加和移除这些对象的方法。您还可以 添加依赖于其他文件或缓存项的对象,并在从 Cache 对象中移除对象时执行回调以通知应用程序。

    protected void Page_Load(object sender, EventArgs e)

       {

           string CacheKey = "cachetest";

           object objModel = GetCache(CacheKey);       //从缓存中获取

           if (objModel == null)                       //缓存里没有

           {

               objModel = DateTime.Now;                //把当前时间进行缓存

               if (objModel != null)

               {

                   int CacheTime = ;                 //缓存时间30秒

                   SetCache(CacheKey, objModel, DateTime.Now.AddSeconds(CacheTime), TimeSpan.Zero);

               }

           }

           Label1.Text = objModel.ToString();

       }

       #region Cache管理

       /// <summary>

       /// 获取当前应用程序指定CacheKey的Cache对象值

       /// </summary>

       /// <param name="CacheKey">索引键值</param>

       /// <returns>返回缓存对象</returns>

       public static object GetCache(string CacheKey)

       {

           System.Web.Caching.Cache objCache = HttpRuntime.Cache;

           return objCache[CacheKey];

       }

       /// <summary>

       /// 设置当前应用程序指定CacheKey的Cache对象值

       /// </summary>

       /// <param name="CacheKey">索引键值</param>

       /// <param name="objObject">缓存对象</param>

       public static void SetCache(string CacheKey, object objObject)

       {

           System.Web.Caching.Cache objCache = HttpRuntime.Cache;

           objCache.Insert(CacheKey, objObject);

       }

       /// <summary>

       /// 设置当前应用程序指定CacheKey的Cache对象值

       /// </summary>

       /// <param name="CacheKey">索引键值</param>

       /// <param name="objObject">缓存对象</param>

       /// <param name="absoluteExpiration">绝对过期时间</param>

       /// <param name="slidingExpiration">最后一次访问所插入对象时与该对象过期时之间的时间间隔</param>

       public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)

       {

           System.Web.Caching.Cache objCache = HttpRuntime.Cache;

           objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);

       }

       #endregion

Cache  Insert 方法 (String, Object, CacheDependency, DateTime, TimeSpan, CacheItemPriority, CacheItemRemovedCallback)

public void Insert(
string key,   //需要添加到Cache中的键
Object value, //对应的值
CacheDependency dependencies, //缓存依赖项 null
DateTime absoluteExpiration, //固定缓存时间 DateTime.Now.AddMinutes(1)
TimeSpan slidingExpiration, //可到延时缓存时间 System.Web.Caching.Cache.NoSlidingExpiration
CacheItemPriority priority, //缓存中的优先级 System.Web.Caching.CacheItemPriority.NotRemovable
CacheItemRemovedCallback onRemoveCallback //移除时调用的回调函数 new System.Web.Caching.CacheItemRemovedCallback(OnMoveCacheBack));
)
 

System.Web.Caching.Cache  Insert和Add区别

  Add方法

object Add(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback);

  Insert方法

void Insert(string key, object value);

void Insert(string key, object value, CacheDependency dependencies);

void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration);

void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemUpdateCallback onUpdateCallback);

void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback);

 比较、区别

a).     Insert方法支持5种重载,使用灵活,而Add方法必须提供7个参数;

b).     Add方法可以返回缓存项的数据对象,Insert 返回Void;

c).     添加重复缓存情况下,Insert会替换该项,而Add方法会报错。

5、文件缓存依赖

这种策略让缓存依赖于一个指定的文件,通过改变文件的更新日期来清除缓存。

    protected void Page_Load(object sender, EventArgs e)

    {

        string CacheKey = "cachetest";

        object objModel = GetCache(CacheKey);//从缓存中获取

        if (objModel == null) //缓存里没有

        {

            objModel = DateTime.Now;//把当前时间进行缓存

            if (objModel != null)

            {

                //依赖 C:\\test.txt 文件的变化来更新缓存

                System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency("C:\\test.txt");

                SetCache(CacheKey, objModel, dep);//写入缓存

            }

        }

        Label1.Text = objModel.ToString();

    }

    #region 缓存管理

    /// <summary>

    /// 获取当前应用程序指定CacheKey的Cache对象值

    /// </summary>

    /// <param name="CacheKey">索引键值</param>

    /// <returns>返回缓存对象</returns>

    public static object GetCache(string CacheKey)

    {

        System.Web.Caching.Cache objCache = HttpRuntime.Cache;

        return objCache[CacheKey];

    }

    /// <summary>

    /// 设置以缓存依赖的方式缓存数据

    /// </summary>

    /// <param name="CacheKey">索引键值</param>

    /// <param name="objObject">缓存对象</param>

    /// <param name="cacheDepen">依赖对象</param>

    public static void SetCache(string CacheKey, object objObject, System.Web.Caching.CacheDependency dep)

    {

        System.Web.Caching.Cache objCache = HttpRuntime.Cache;

        objCache.Insert(

            CacheKey,

            objObject,

            dep,

            System.Web.Caching.Cache.NoAbsoluteExpiration, //从不过期

            System.Web.Caching.Cache.NoSlidingExpiration, //禁用可调过期

            System.Web.Caching.CacheItemPriority.Default,

            null);

    }

    #endregion

当我们改变test.txt的内容时,缓存会自动更新。这种方式非常适合读取配置文件的缓存处理。如果配置文件不变化,就一直读取缓存的信息,一旦配置发生变化,自动更新同步缓存的数据。

这种方式的缺点是,如果缓存的数据比较多,相关的依赖文件比较松散,对管理这些依赖文件有一定的麻烦。对于负载均衡环境下,还需要同时更新多台Web服务器下的缓存文件,如果多个Web应用中的缓存依赖于同一个共享的文件,可能会省掉这个麻烦。

如何:从缓存中移除项时通知应用程序

在大多数缓存方案中,当从缓存中移除一个项时,不必通知您该项已被移除。典型的开发模式是在使用项之前始终检查该项是否已在缓存中。如果项位于缓存中,则可以使用。如果不在缓存中,则应再次检索该项,然后将其添加回缓存。

但是,在某些情况下,如果从缓存中移除项时通知应用程序,可能非常有用。例如,您可能希望跟踪从缓存中移除项的时间和原因,以便对缓存设置进行调整。

为了在从缓存中移除项时能够发出通知,ASP.NET 提供了 CacheItemRemovedCallback 委托。 该委托为事件处理程序定义签名,以便在从缓存中移除项时调用该事件处理程序。通常,可通过在管理缓存数据的业务对象中创建一个处理程序来实现回调。

示例

下面的示例将演示一个名为 ReportManager 的类。 此类的 GetReport 方法会创建一个由字符串“Report Text”组成的报告。 该方法将此报告保存在缓存中,在随后调用该方法时,它将从缓存中检索此报告。

如果两次调用 GetReport 的时间间隔超过 15 秒,则 ASP.NET 将会从缓存中移除此报告。 当发生该事件时,将调用 ReportManager 类的 ReportRemovedCallback 方法。 此方法将私有成员变量设置为“Re-created [date and time]”,其中 [date and time] 为当前的日期和时间。 下一次调用 GetReport 时(在缓存项到期之后),该方法将重新创建报告,并将 ReportRemovedCallback 方法设置的变量值追加到该报告中。 ShowReport.aspx 页会显示 GetReport 返回的报告字符串,其中包括最后一次重新创建报告的日期和时间。

若要查看此行为,请加载该页面并等待,15 秒过后,再在浏览器中重新加载该页面。您将看到添加到报告文本中的日期和时间。

using System;

using System.Text;

using System.Web;

using System.Web.Caching;

public static class ReportManager

{

    private static string _lastRemoved = "";

    public static String GetReport()

    {

        string report = HttpRuntime.Cache["MyReport"] as string;

        if (report == null)

        {

            report = GenerateAndCacheReport();

        }

        return report;

    }

    private static string GenerateAndCacheReport()

    {

        string report = "Report Text. " + _lastRemoved.ToString();

        HttpRuntime.Cache.Insert(

            "MyReport",

            report,

            null,

            Cache.NoAbsoluteExpiration,

            new TimeSpan(, , ),

            CacheItemPriority.Default,

            new CacheItemRemovedCallback(ReportRemovedCallback));

        return report;

    }

    public static void ReportRemovedCallback(String key, object value,

        CacheItemRemovedReason removedReason)

    {

        _lastRemoved = "Re-created " + DateTime.Now.ToString();

    }

}
<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <%=ReportManager.GetReport() %>

    </div>

    </form>

</body>

</html>

Cache 应用程序数据缓存的更多相关文章

  1. ASP.NET缓存全解析4:应用程序数据缓存 转自网络原文作者李天平

    System.Web.Caching 命名空间提供用于缓存服务器上常用数据的类.此命名空间包括 Cache 类,该类是一个字典,您可以在其中存储任意数据对象,如哈希表和数据集.它还为这些对象提供了失效 ...

  2. 微信小程序-数据缓存

    每个微信小程序都可以有自己的本地缓存,可以通过 wx.setStorage(wx.setStorageSync).wx.getStorage(wx.getStorageSync).wx.clearSt ...

  3. 「小程序JAVA实战」小程序数据缓存API(54)

    转自:https://idig8.com/2018/09/22/xiaochengxujavashizhanxiaochengxushujuhuancunapi52/ 刚开始写小程序的时候,用户信息我 ...

  4. .net 缓存之应用程序数据缓存

    CaCheHelp类中代码如下: #region 根据键从缓存中读取保持的数据 /// <summary> /// 根据键从缓存中读取保持的数据 /// </summary> ...

  5. .NET使用HttpRuntime.Cache设置程序定时缓存

    第一步:判断读取缓存数据 #region 缓存读取 if (HttpRuntime.Cache["App"] != null) { return HttpRuntime.Cache ...

  6. cache应用(asp.net 2.0 SQL数据缓存依赖 [SqlCacheDependency ] )

    Asp.net 2.0 提供了一个新的数据缓存功能,就是利用sql server2005 的异步通知功能来实现缓存 1.首先在sqlserver2005 中创建一个test的数据库. 在SQL Ser ...

  7. SQL数据缓存依赖 [SqlServer | Cache | SqlCacheDependency ]

    前言 本文主要是对<ASP.NET 2.0开发指南>——<数据缓存>章节内容的提取并略有补充. 参考资料 1.     <ASP.NET 2.0开发指南> 2.   ...

  8. 微信小程序 API 数据缓存

    微信小程序 数据缓存 (类似于 cookie) wx.setStorage() 将数据存储在本地缓存中制定的 key 中.会覆盖掉原来该 key 对应的内容,数据存储生命周期跟小程序本身一致,即除用户 ...

  9. SQL SERVER 2000 & SQL SERVER 2005 数据缓存依赖

    一.SQL SERVER 7.0/2000和SQL SERVER 2005的简介及比较 1.1     SQL SERVER 7.0/2000 SQL SERVER 7.0/2000没有提供内置的支持 ...

随机推荐

  1. 什么是AJAX技术及其常识

    1.什么是Ajax? Ajax的全称是:AsynchronousJavaScript+XML 2.Ajax的定义: Ajax不是一个技术,它实际上是几种技术,每种技术都有其独特这处,合在一起就成了一个 ...

  2. 关于PHP Websocket 错误: "stream_select(): You MUST recompile PHP with a larger value of FD_SETSIZE" 的解决方案

    最近在使用Ratchet (一个PHP websocket框架)改造一个PHP网站的时候,出现了错误: "It is set to 1024, but you have descriptor ...

  3. XE5 ANDROID通过webservice访问操作MSSQL数据库

    上接XE5 ANDROID平台 调用 webservice 一.服务端 在ro里添加函数(在impl上添加阿东connection,adoquery,dataprovider) function TN ...

  4. Response.Redirect和Server.Transfer

    今天又比较闲,逛了逛园子,看看asp.net的内容,看到一篇关于这两个的比较: http://www.cnblogs.com/yunfeng8967/archive/2008/03/06/109323 ...

  5. openerp经典收藏 深入理解报表运行机制(转载)

    深入理解报表运行机制 原文:http://blog.sina.com.cn/s/blog_57ded94e01014ppd.html 1) OpenERP报表的基本运行机制    OpenERP报表的 ...

  6. Hadoop2安装

    http://wenku.baidu.com/view/fe1b2f22de80d4d8d15a4f6e.html http://wenku.baidu.com/view/e4607031581b6b ...

  7. python之域与属性

    python, javascript中域与属性是二个不同的概念, 域就是变量, 而属性则是符合某些约束, 例如getter, setter...等的特殊"变量". python中使 ...

  8. 学习asp.net mvc5心得

    前几天时间大体学习了一下asp.net mvc5的应用,感觉最主要的就是要区分这以模式设计,其他的都是在asp.net下的基础操作 1参数的传递注意 2路由的设置规则 3model的应用

  9. 关于const

    1.顶层const和底层const const修饰的对象本身是常量,则为顶层const,否则为底层const 如: const int a=10;        //a是int常量,顶层const i ...

  10. cocos2dx中的坐标体系

    1.UI坐标系和GL坐标系 2.本地坐标与世界坐标 本地坐标是一个相对坐标,是相对于父节点或者你指明的某个节点的相对位置来说的,本地坐标的原点在参考节点的左下角 世界坐标是一个绝对的坐标,是以屏幕的左 ...