如何迭代缓存条目

新手上路,请多包涵

我在独立环境中使用 Spring3.1。我正在使用 @Cachable 注释缓存我的条目。

有时我需要迭代缓存列表以获得 特定值(不是键)。

所以我设法检索了缓存列表,但我怎么能迭代它的元素。

 private ClientDTO getClientDTOByClientId(Integer clientId)
{

    Cache clientCache = null;
    try
    {
        clientCache = ehCacheCacheManager.getCache("client");

          //need here to iterate on clientCache. how?

    }
    catch (Exception e)
    {
        log.error("Couldnt retrieve client from cache. clientId=" + clientId);
    }
    return clientDTO;
}

我使用 ehcache 机制。

 <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
        p:cache-manager-ref="ehcache" />

    <bean id="ehcache"
        class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
        p:config-location="classpath:ehcache.xml" />

谢谢,雷。

原文由 rayman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 501
2 个回答

CacheManager.getCache() 返回一个 net.sf.ehcache.Cache,它有一个 getKeys() 方法,它返回一个可以迭代的缓存键列表。要检索已存储的实际对象(与包装的 net.sf.ehcache.Element 相对),请使用 Element.getObjectValue()。

编辑:根据 Spring 的说法, 它们看起来永远不会支持 Cache.getKeys() ,因此您必须转换为底层提供程序。

是这样的:

 public boolean contains(String cacheName, Object o) {
  net.sf.ehcache.EhCache cache = (net.sf.ehcache.EhCache) org.springframework.cache.CacheManager.getCache(cacheName).getNativeCache();
  for (Object key: cache.getKeys()) {
    Element element = cache.get(key);
    if (element != null && element.getObjectValue().equals(o)) {
      return true;
    }
  }
  return false;
}

原文由 Matt Brock 发布,翻译遵循 CC BY-SA 3.0 许可协议

另一种解决方案,使用 getNativeCache() 方法将 org.springframework.cache.Cache 转换为 javax.cache.Cache,并使用 java 迭代器,因为 javax.cache.Cache 已经扩展了 Iterable>。

有关详细信息,请阅读 javax.cache.Cache javadoc

     Cache cache = (Cache) cacheManager.getCache("yourCacheName").getNativeCache();
    Iterator<Cache.Entry> iterator = cache.iterator();

    while (iterator.hasNext()) {
        String key = (String) iterator.next().getKey();
        System.out.println(key);
    }

原文由 Abdelrahman Elattar 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题