Search code examples
javaspringcachingehcache

How to Iterate on a cache entries


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

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

thanks, ray.


Solution

  • 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().

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

    Something like this:

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