如何找出缓存管理器中是否存在密钥 (org.springframework.cache.CacheManager)

How to find out if key exist in cacheManager (org.springframework.cache.CacheManager)

有没有办法查看 cacheManager (org.springframework.cache.CacheManager) 中是否存在特定键,因为没有 containsKey 选项,我无法找到这样做的方法。如果有人能告诉我一种检查 cacheManager 中是否存在密钥的方法,我将不胜感激。以下是我到目前为止尝试过的一些东西 -

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 
    }

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

您可以简单地检查 Cache.getnull 返回的值。

来自relevant documentation(我强调):

Returns the value to which this cache maps the specified key, contained within a Cache.ValueWrapper which may also hold a cached null value. A straight null being returned means that the cache contains no mapping for this key.

所以

  • cache.get("foo") == null表示:key"foo"在缓存中不存在
  • cache.get("foo").get() == null表示:缓存中确实存在键"foo",但其值为null