如何对缓存条目进行迭代 [英] How to Iterate on a cache entries

查看:42
本文介绍了如何对缓存条目进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在独立Env中使用Spring3.1.我正在使用@Cachable注释缓存条目.

I am using Spring3.1 in standalone Env. I am caching my entry using @Cachable annotation.

有时候我需要在缓存列表上进行迭代,以获得特定值(不是键).

Sometimes I need to iterate on the caching list in order to get specific value(not key).

因此我设法检索了缓存列表,但是如何对其元素进行迭代.

So I managed to retrieve the cached list but how could I iterate on it's elements.

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机制.

I using ehcache mechanism.

<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" />

谢谢,射线.

推荐答案

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

CacheManager.getCache() returns a net.sf.ehcache.Cache, which has a getKeys() method that returns a list of cache keys that you can iterate over. To retrieve the actual object that's been stored (as opposed to the wrapped net.sf.ehcache.Element), use the Element.getObjectValue().

根据Spring 看来,他们似乎永远不会支持Cache.getKeys(),因此您必须转换为基础提供程序.

According to Spring it doesn't look like they will ever support Cache.getKeys(), so you'll have to cast to the underlying provider.

类似这样的东西:

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;
}

这篇关于如何对缓存条目进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆