Redis:基于依赖项的缓存项无效



当从缓存中删除其他指定项时,Redis中是否有本机方法使缓存项无效?是否有基于依赖关系的驱逐政策?

下面是我想要完成的一个例子。

假设在Redis中,我们有一个缓存项,其键为mainKey。如果删除了另一个特定项目,我希望自动删除此项目。例如,如果mainKey依赖键d1d2,则我希望在从缓存中移除d1d2后立即将

mainKey例如,在.Net中,使用MemoryCache编写这样的代码相当容易。

[TestMethod]
public void TestCacheItemIsRemovedWhenADependencyGetsRemoved() {
// ARRANGE
var cache = new MemoryCache(name: "MyCache");
// insert dependencies cache items
var dummyValue = 1;
cache.Set("d1", dummyValue, absoluteExpiration: DateTime.Now.AddDays(1));
cache.Set("d2", dummyValue, absoluteExpiration: DateTime.Now.AddDays(1));
// build cache policy for main cache item
var policy = new CacheItemPolicy {
SlidingExpiration = TimeSpan.FromMinutes(10)
};
var dependencies = new[] { "d1", "d2" };
var changeMonitor = cache.CreateCacheEntryChangeMonitor(dependencies);
policy.ChangeMonitors.Add(changeMonitor);
// insert main cache item
cache.Set("mainKey", "this is the main value", policy);
// ACT
// remove a dependency key
cache.Remove("d1");
// ASSERT
// mainKey is removed as a consequence of removing "d1"
Assert.IsFalse(cache.Contains("mainKey"));
// only "d2" remains in the cache
Assert.AreEqual(1, cache.GetCount());
Assert.IsTrue(cache.Contains("d2"));
}

这是缓存失效中的一个已知障碍,您需要缓存标记来克服它。

例如,mainKey依赖于键d1和d2,那么我希望在从缓存中删除d1或d2后立即从缓存中移除mainKey。

TL;DR-您需要标记相互依赖的密钥,当其中一个密钥发生某些操作(更新或删除(时,您需要删除共享同一标记的所有缓存项。

最新更新