Cache 应用程序数据缓存

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;                 //缓存时间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)); )
 
2010-10-13_00068

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(0, 0, 15),

            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>
原文地址:https://www.cnblogs.com/ChineseMoonGod/p/5202892.html