0

I have a problem when trying to get back a Guava cache from a cache manager, instead I get a Spring Cache.

This is the bean in my SpringConfig file :

@Bean
public CacheManager cacheManager() {
    ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager() {

        @Override
        protected Cache createConcurrentMapCache(final String name) {
            return new ConcurrentMapCache(name, CacheBuilder.newBuilder().expireAfterWrite(1440, TimeUnit.MINUTES)
                    .maximumSize(100).recordStats().build().asMap(), false); }
    };
    return cacheManager;
}

And then I'm able to use the @Cacheable :

@Cacheable(value = "myCache")
public void myCacheMethod(String key){
    // call a web service
}

Everything works fine, but I can't get the cache Guava object created by the CacheBuilder in order to call the stats() method.

This is how I get the cache :

Cache myCache = cacheManager.getCache("myCache");
ValueWrapper wrapper = myCache.get("key");
WebServiceType myCachedObject= (WebServiceType) wrapper.get();

The last cache is a Spring cache, and I get an error if I cast it to Guava cache.

Is this possible ? Or did I do something wrong ?

StepUp
  • 36,391
  • 15
  • 88
  • 148
yoann let
  • 31
  • 8
  • Why do you need the cache? Spring provides an abstraction over several caching solution so casting won't work, generally you wouldn't need nor should access the cache directly. Generally a sign you are doing something you shouldn't be doing in the first place. – M. Deinum Apr 04 '16 at 08:49
  • I'm using Guava cache for the TTL and maximum size. – yoann let Apr 04 '16 at 09:03
  • So then why do you need access to the cache? You can configure all that with the `CacheBuilder`? Also I suggest using the direct support with the [`GuaveCacheManager`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/cache/guava/GuavaCacheManager.html) instead of trying to wrap it in a concurrent map. – M. Deinum Apr 04 '16 at 09:23
  • I want to use the stats() method. Unfortunatly I can't use the GuavaCacheManager since it is not available with the Spring version I use. – yoann let Apr 04 '16 at 09:34
  • Then upgrade, what you have now won't work. As you are using a `MapCache` which uses a `Map` which in turn doesn't know anything about `Guava`. Again looks like you are trying to do something you shouldn't be doing in the first place. Why do you need to call that method? – M. Deinum Apr 04 '16 at 09:37
  • I wanted to know how many times my cache was called, etc. I think I have to find something else. Anyway thanks for your help. – yoann let Apr 04 '16 at 09:43
  • You can try register them as JMX. Before converting it to a `Map`, wrap it in a JMX bean to get the underlying stats. See https://gist.github.com/kofemann/6702006 which you can probably combine with a spring exposed `MBeanServer`. That way you can use JMX to obtain the stats. – M. Deinum Apr 04 '16 at 09:51

0 Answers0