【缓存】系统缓存全解析 (中)

 

4、应用程序数据缓存

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

 

隐藏行号 复制代码
  1. protected void Page_Load(object sender, EventArgs e)
    
  2.    {
    
  3.        string CacheKey = "cachetest";
    
  4.        object objModel = GetCache(CacheKey);       //从缓存中获取
    
  5. 
    
  6.        if (objModel == null)                       //缓存里没有
    
  7.        {
    
  8. 
    
  9.            objModel = DateTime.Now;                //把当前时间进行缓存
    
  10. 
    
  11.            if (objModel != null)
    
  12.            {
    
  13.                int CacheTime = 30;                 //缓存时间30秒
    
  14.                SetCache(CacheKey, objModel, DateTime.Now.AddSeconds(CacheTime), TimeSpan.Zero);
    
  15. 
    
  16.            }
    
  17.        }
    
  18. 
    
  19.        Label1.Text = objModel.ToString();
    
  20.    }
    
  21. 
    
  22.    #region Cache管理
    
  23. 
    
  24.    /// <summary>
    
  25.    /// 获取当前应用程序指定CacheKey的Cache对象值
    
  26.    /// </summary>
    
  27.    /// <param name="CacheKey">索引键值</param>
    
  28.    /// <returns>返回缓存对象</returns>
    
  29.    public static object GetCache(string CacheKey)
    
  30.    {
    
  31.        System.Web.Caching.Cache objCache = HttpRuntime.Cache;
    
  32.        return objCache[CacheKey];
    
  33.    }
    
  34. 
    
  35.    /// <summary>
    
  36.    /// 设置当前应用程序指定CacheKey的Cache对象值
    
  37.    /// </summary>
    
  38.    /// <param name="CacheKey">索引键值</param>
    
  39.    /// <param name="objObject">缓存对象</param>
    
  40. 
    
  41.    public static void SetCache(string CacheKey, object objObject)
    
  42.    {
    
  43.        System.Web.Caching.Cache objCache = HttpRuntime.Cache;
    
  44.        objCache.Insert(CacheKey, objObject);
    
  45.    }
    
  46. 
    
  47.    /// <summary>
    
  48.    /// 设置当前应用程序指定CacheKey的Cache对象值
    
  49.    /// </summary>
    
  50.    /// <param name="CacheKey">索引键值</param>
    
  51.    /// <param name="objObject">缓存对象</param>
    
  52.    /// <param name="absoluteExpiration">绝对过期时间</param>
    
  53.    /// <param name="slidingExpiration">最后一次访问所插入对象时与该对象过期时之间的时间间隔</param>
    
  54.    public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
    
  55.    {
    
  56.        System.Web.Caching.Cache objCache = HttpRuntime.Cache;
    
  57.        objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);
    
  58.    }
    
  59. 
    
  60.    #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、文件缓存依赖

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

隐藏行号 复制代码
  1. protected void Page_Load(object sender, EventArgs e)
    
  2. {
    
  3.     string CacheKey = "cachetest";
    
  4.     object objModel = GetCache(CacheKey);//从缓存中获取
    
  5.     if (objModel == null) //缓存里没有
    
  6.     {
    
  7.         objModel = DateTime.Now;//把当前时间进行缓存
    
  8.         if (objModel != null)
    
  9.         {
    
  10.             //依赖 C:\test.txt 文件的变化来更新缓存
    
  11.             System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency("C:\test.txt");
    
  12.             SetCache(CacheKey, objModel, dep);//写入缓存
    
  13.         }
    
  14.     }
    
  15.     Label1.Text = objModel.ToString();
    
  16. }
    
  17. 
    
  18. #region 缓存管理
    
  19. 
    
  20. /// <summary>
    
  21. /// 获取当前应用程序指定CacheKey的Cache对象值
    
  22. /// </summary>
    
  23. /// <param name="CacheKey">索引键值</param>
    
  24. /// <returns>返回缓存对象</returns>
    
  25. public static object GetCache(string CacheKey)
    
  26. {
    
  27.     System.Web.Caching.Cache objCache = HttpRuntime.Cache;
    
  28.     return objCache[CacheKey];
    
  29. }
    
  30. 
    
  31. /// <summary>
    
  32. /// 设置以缓存依赖的方式缓存数据
    
  33. /// </summary>
    
  34. /// <param name="CacheKey">索引键值</param>
    
  35. /// <param name="objObject">缓存对象</param>
    
  36. /// <param name="cacheDepen">依赖对象</param>
    
  37. public static void SetCache(string CacheKey, object objObject, System.Web.Caching.CacheDependency dep)
    
  38. {
    
  39. 
    
  40.     System.Web.Caching.Cache objCache = HttpRuntime.Cache;
    
  41.     objCache.Insert(
    
  42.         CacheKey,
    
  43.         objObject,
    
  44.         dep,
    
  45.         System.Web.Caching.Cache.NoAbsoluteExpiration, //从不过期
    
  46.         System.Web.Caching.Cache.NoSlidingExpiration, //禁用可调过期
    
  47.         System.Web.Caching.CacheItemPriority.Default,
    
  48.         null);
    
  49. 
    
  50. }
    
  51. 
    
  52. #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 秒过后,再在浏览器中重新加载该页面。您将看到添加到报告文本中的日期和时间。

隐藏行号 复制代码
  1. using System;
    
  2. using System.Text;
    
  3. using System.Web;
    
  4. using System.Web.Caching;
    
  5. 
    
  6. public static class ReportManager
    
  7. {
    
  8.     private static string _lastRemoved = "";
    
  9. 
    
  10.     public static String GetReport()
    
  11.     {
    
  12.         string report = HttpRuntime.Cache["MyReport"] as string;
    
  13.         if (report == null)
    
  14.         {
    
  15.             report = GenerateAndCacheReport();
    
  16.         }
    
  17.         return report;
    
  18.     }
    
  19. 
    
  20.     private static string GenerateAndCacheReport()
    
  21.     {
    
  22.         string report = "Report Text. " + _lastRemoved.ToString();
    
  23. 
    
  24.         HttpRuntime.Cache.Insert(
    
  25.             "MyReport",
    
  26.             report,
    
  27.             null,
    
  28.             Cache.NoAbsoluteExpiration,
    
  29.             new TimeSpan(0, 0, 15),
    
  30.             CacheItemPriority.Default,
    
  31.             new CacheItemRemovedCallback(ReportRemovedCallback));
    
  32. 
    
  33.         return report;
    
  34.     }
    
  35. 
    
  36.     public static void ReportRemovedCallback(String key, object value,
    
  37.         CacheItemRemovedReason removedReason)
    
  38.     {
    
  39.         _lastRemoved = "Re-created " + DateTime.Now.ToString();
    
  40.     }
    
  41. }
    
隐藏行号 复制代码
  1. <%@ Page Language="C#" AutoEventWireup="true" %>
    
  2. 
    
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
  4. 
    
  5. <html xmlns="http://www.w3.org/1999/xhtml">
    
  6. <head id="Head1" runat="server">
    
  7.     <title></title>
    
  8. </head>
    
  9. <body>
    
  10.     <form id="form1" runat="server">
    
  11.     <div>
    
  12.     <%=ReportManager.GetReport() %>
    
  13.     </div>
    
  14.     </form>
    
  15. </body>
    
  16. </html>
    
  17. 
    
原文地址:https://www.cnblogs.com/jx270/p/4212252.html