【问题标题】:Clean cache based on DependencyKey根据依赖键清除缓存
【发布时间】:2023-04-09 09:46:01
【问题描述】:

基于日期时间值,我将值插入缓存:

Dim Value1 As String = "value1"
Dim Value2 As String = "value2"
Dim Key1 As String = "Key" & New Date(2014, 1, 1, 1, 1, 0).ToString
Dim Key2 As String = "Key" & New Date(2014, 1, 1, 1, 2, 0).ToString
HttpContext.Current.Cache.Insert(Key1, Value1)
HttpContext.Current.Cache.Insert(Key2, Value2)

是否可以使用另一个缓存项作为 CacheDependency 使这些缓存项失效?

我尝试了以下方法,但这不起作用:

Dim Keys As String() = New String(0) {}
Keys(0) = "OtherKey"
Dim MyDependency As New System.Web.Caching.CacheDependency(Nothing, Keys)
HttpContext.Current.Cache.Insert(Key1, Value1, MyDependency)
HttpContext.Current.Cache.Insert(Key2, Value2, MyDependency)

'To clear all cache items:
HttpContext.Current.Cache.Remove("OtherKey")

当我使用它(没有删除语句)时,永远无法在缓存中找到这些项目。我在这里做错了什么?

【问题讨论】:

    标签: .net vb.net caching


    【解决方案1】:

    如果您想将 CacheDependency 用于另一个缓存键:

    • 您所依赖的密钥(即OtherKey)必须在缓存中找到(参见this article)。否则将无法在缓存中找到您的项目。
    • 您需要为每个项目创建不同的 CacheDependency 实例。否则会报错An attempt was made to reference a CacheDependency object from more than one Cache entry(见this question的答案)

    所以你插入项目的代码是这样的:

    ' Make sure OtherKey is found in the cache
    HttpContext.Current.Cache.Insert("OtherKey", "SomeValue")
    
    ' Add the items with a different CacheDependency instance per item
    Dim Keys As String() = New String(0) {}
    Keys(0) = "OtherKey"
    HttpContext.Current.Cache.Insert(Key1, Value1, New System.Web.Caching.CacheDependency(Nothing, Keys))
    HttpContext.Current.Cache.Insert(Key2, Value2, New System.Web.Caching.CacheDependency(Nothing, Keys))
    
    • 请注意,如果您不添加键为 OtherKey 的缓存项,将永远找不到依赖项。

    那么当你从缓存中移除OtherKey时,依赖项会被自动移除。所以这一行会自动从缓存中删除 Key1Key2

    HttpContext.Current.Cache.Remove("OtherKey")
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2010-12-24
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多