0

Ehcache isn't working properly in my project. I run grails 3.3.1 "with org.grails.plugins:cache-ehcache:3.0.0.M1" and since i dont know where to put the ehcache.xml file and how the file should look like i tried to configure ehcache programmaticially

I created a cacheService with a methode "initCaches" which i run from my bootstrap.groovy

class CacheService {
void initCaches() {       
    CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
        .withCache("sevenSeconds", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10))
            .withExpiry(Expirations.timeToLiveExpiration(Duration.of(7, TimeUnit.SECONDS)))
        )
        .withCache("twentySeconds", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10))
            .withExpiry(Expirations.timeToLiveExpiration(Duration.of(20, TimeUnit.SECONDS)))
        )
        .build()  
    cacheManager.init()
}
}

When I start the application the console says that the caches have been created:

2018-06-26 15:47:31.302  INFO --- [           main] org.ehcache.core.EhcacheManager          : Cache 'sevenSeconds' created in EhcacheManager.
2018-06-26 15:47:31.310  INFO --- [           main] org.ehcache.core.EhcacheManager          : Cache 'twentySeconds' created in EhcacheManager.

Now I access a service method which is annotated with @Cacheable("sevenSeconds") and there comes the part which is confusing me: Again the console says, that the cache has been created (instead of putting the result into the old already out of CacheService created one):

2018-06-26 15:47:31.302  INFO --- [           main] org.ehcache.core.EhcacheManager          : Cache 'sevenSeconds' created in EhcacheManager.

If i access the service again with same parameters a cached result will returned BUT the timeToLive is NOT 7 seconds like I created the cache in my CacheService.

It looks like @Cacheable doesn't consider my created caches in CacheService

Does anybody know what I am doing wrong?

thx

pebbles
  • 356
  • 1
  • 3
  • 19

1 Answers1

0

I don't know how Grails manage the CacheService and how initCaches is called. However, your CacheManager is a local variable. So I would expect it to be garbage collected at the end of initCaches.

@Cacheable is probably using some other CacheManager. So that's what you should fix by making the CacheManager created in initCaches available to Grails expected convention.

Henri
  • 5,551
  • 1
  • 22
  • 29
  • so the scope is different between creating the cache via ehcache.xml and the programmaticial way? – pebbles Jul 02 '18 at 09:39
  • The scope? I am talking about the `cacheManager` variable. Its scope is local to the method. – Henri Jul 02 '18 at 17:31
  • well i haven't found a way to make the programaticially created cacheManager global. so i configured the cacheManager via xml file – pebbles Jul 09 '18 at 10:59