如何查明key是否存在于cacheManager中(org.springframework.cache.CacheManager)

Jon*_*ham 3 caching infinispan spring-boot

有没有办法查看cacheManager(org.springframework.cache.CacheManager)中是否存在特定的键,因为我无法找到一种方法来做到这一点,因为没有containsKey选项。如果有人可以向我展示一种检查缓存管理器中是否存在密钥的方法,我将不胜感激。以下是我迄今为止尝试过的一些事情 -

Cache cache=null;
for (String name : cacheManager.getCacheNames()) {
    cache=cacheManager.getCache(name);
    System.out.println("-------------->"+cache.get("dummyCache").get()); //this will give me null pointer exception as there is no dummyCache 
    }
Run Code Online (Sandbox Code Playgroud)

我想添加 if/else 检查以查看dummyCache缓存中是否存在密钥

Mar*_*vin 7

Cache.get您可以简单地检查for返回的值null

相关文档(我强调的):

返回此缓存将指定键映射到的值,该值包含在 Cache.ValueWrapper 中,该值也可能保存缓存的 null 值。返回的直接 null 意味着缓存不包含该键的映射。

所以

  • cache.get("foo") == null意思是:缓存中不存在键“foo”
  • cache.get("foo").get() == null意思是:键“foo”确实存在于缓存中,但其值为null