0

I got an issue where the method on my service has annotation that looks like the following:

@Cacheable(value = "myCache", key = "'myCache' + #listType", unless = "#result.getMyList().size() == 0")

On my EhCacheConfig I have that looks like the following:

 @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        List<Cache> caches = new ArrayList<Cache>();
        caches.add(new ConcurrentMapCache("myCache"));
        cacheManager.setCaches(caches);
        return cacheManager;
    }

The cache works just as I expect it to but now I need to have a persistent storage and I can only find how to do it with PersistentCacheManager. when I try to implement it following EhCache documentation I keep getting an error:

"Cannot find cache named 'myCache' for Builder

This is my EhCacheConfig when implementing PersistentCacheManager:

@Bean
    public PersistentCacheManager cacheManager() {
        PersistentCacheManager persistentCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
                .with(CacheManagerBuilder.persistence(new File(storagePath, "myData")))
                .withCache("myCache", CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, NotificationListResponse.class,
                        ResourcePoolsBuilder.newResourcePoolsBuilder()
                                .disk(10, MemoryUnit.MB, true))
                )
                .build();
        persistentCacheManager.init(true);
        return persistentCacheManager;
    }
Paloma Schkrab
  • 301
  • 1
  • 4
  • 13

1 Answers1

0

Solved the issue with the following:

did not need the bean above and created a CacheHelper

private String storagePath = "home\\parentFolder\\cache";

private PersistentCacheManager persistentCacheManager;
private Cache<String, String> myCache;

public EhCacheHelper() {
    persistentCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
            .with(CacheManagerBuilder.persistence(new File(storagePath, "myData")))
            .withCache("myCache", CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
                    ResourcePoolsBuilder.newResourcePoolsBuilder()
                            .disk(10, MemoryUnit.MB, true))
            )
            .build(true);
}

public Cache<String, NotificationListResponse> getMyCacheFromCacheManager() {
    return persistentCacheManager.getCache("myCache", String.class, String.class);
}

on the method I wanted cached, instead of having the Cacheable annotation, added code to access and save data to cache like:

if (cache.getMyCacheFromCacheManager().containsKey(myKey)) {
    return cache.getMyCacheFromCacheManager().get(myKey);
}
.
.
.
cache.getMyCacheFromCacheManager().put(myKey, myValue);
Paloma Schkrab
  • 301
  • 1
  • 4
  • 13