ASP.NET缓存:缓存移除项时通知应用程序

1、Asp.net提供了CacheItemRemovedCallback委托来实现缓存移除时通知应用程序。在业务类中只需实现一个与CacheItemRemovedCallback委托相同签名的方法。

2、可以通过创建缓存的Insert方法实现,也可以通过创建缓存的Add方法实现。

3、定义回调方法的相同签名的委托如下

public delegate void CacheItemRemovedCallback(
    string key,
    Object value,
    CacheItemRemovedReason reason
)

key:类型:System.String 从缓存中移除的键

value:类型:System.Object CacheItemRemovedReason枚举指定的、从缓存移除项的原因。

指定从Cache对象移除项的原因。该对象枚举值如下

Removed:移除原因为用Insert方添加项到缓存时指定键与移除项键相同或者用Remove方法移除缓存项。

Expired:移除原因为缓存项过期。

Underused:移除原因为系统需通过移除该项释放内存。

DependencyChanged:移除原因为该缓存的依赖项发生改变。

5、下例实现当缓存项移除时,获取移除时间及原因

    public static class ReportManager
    {
        private static bool itemRemoved = false;//缓存项是否被移除
        private static CacheItemRemovedReason reason;//缓存项移除原因
        private static string lastRemovedTime = "";//上次缓存项移除时间

        public static string GetReport()
        {
            string reportItem=HttpRuntime.Cache["MyReport"] as string;
            if (reportItem == null)
            {
                GenerateCacheReport();
            }
            
            //输出上次缓存移除的时间及原因
            string report=string.Empty;
            if (itemRemoved)
            {
                report = "LastRemoved time:" + lastRemovedTime.ToString()
                    + "  LastRemoved reason:" + reason.ToString();
            }
            return report;
        }

        private static void GenerateCacheReport()
        {
            //把项添加到缓存中
            HttpRuntime.Cache.Insert("MyReport", "report",
                null, Cache.NoAbsoluteExpiration,
                new TimeSpan(0, 0, 15),
                CacheItemPriority.Default,
                new CacheItemRemovedCallback(ReportRemovedCallBack));
        }
        public static void ReportRemovedCallBack(string key, object value,
            CacheItemRemovedReason removedReason)
        {
            itemRemoved = true;
            reason = removedReason;
            lastRemovedTime = DateTime.Now.ToString();
        }
    }

输出缓存移除时间及原因到前台页面

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>记录缓存移除时时间及原因</title>
</head>
<body>
    <form  runat="server">
    <div>
    <%=ReportManager.GetReport() %>
    </div>
    </form>
</body>
</html>