7

For now I have following config:

@Configuration
@EnableCaching
public class EhcacheConfig {
    @Bean
    public CacheManager cacheManager() throws URISyntaxException {
        return new JCacheCacheManager(Caching.getCachingProvider().getCacheManager(
                getClass().getResource("/ehcache.xml").toURI(),
                getClass().getClassLoader()
        ));
    }
}

It refers to the following XML:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://www.ehcache.org/v3"
        xmlns:jsr107="http://www.ehcache.org/v3/jsr107"
        xsi:schemaLocation="
            http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd
            http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">

    <cache alias="pow_cache">
        <key-type>org.springframework.cache.interceptor.SimpleKey</key-type>
        <value-type>java.lang.Double</value-type>
        <expiry>
            <ttl unit="seconds">15</ttl>
        </expiry>

        <listeners>
            <listener>
                <class>my.pack.CacheEventLogger</class>
                <event-firing-mode>ASYNCHRONOUS</event-firing-mode>
                <event-ordering-mode>UNORDERED</event-ordering-mode>
                <events-to-fire-on>CREATED</events-to-fire-on>
                <events-to-fire-on>EXPIRED</events-to-fire-on>
            </listener>
        </listeners>

        <resources>
            <heap unit="entries">2</heap>
            <offheap unit="MB">10</offheap>
        </resources>
    </cache>

</config>

And service look like this:

@Cacheable(value = "pow_cache", unless = "#pow==3||#result>100", condition = "#val<5")
public Double pow(int val, int pow) throws InterruptedException {
    System.out.println(String.format("REAL invocation myService.pow(%s, %s)", val, pow));
    Thread.sleep(3000);
    return Math.pow(val, pow);
}

It works properly but I want to get free of xml configuration.

I've read and tried to apply following answer(last piece of code) But it works only for Ehcache 2 but I am going to use Eehcache 3

How can I achieve it ?

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

2 Answers2

11

As EhCache seems to be JSR-107 compliant, you'll need to use it this way to have a programatic configuration:

@Bean
public CacheManager cacheManager() throws URISyntaxException {
    CachingProvider provider = Caching.getCachingProvider();  
    CacheManager cacheManager = provider.getCacheManager();   

    CacheConfigurationBuilder<SimpleKey, Double> configuration = 
    CacheConfigurationBuilder.newCacheConfigurationBuilder(org.springframework.cache.interceptor.SimpleKey.class,
        java.lang.Double.class, 
        ResourcePoolsBuilder.heap(2).offheap(10, MemoryUnit.MB))
        .withExpiry(Expirations.timeToLiveExpiration(new Duration(15, TimeUnit.SECONDS)));

    Cache cache = cacheManager.createCache("pow_cache", configuration);
    cache.getRuntimeConfiguration().registerCacheEventListener(listener, EventOrdering.UNORDERED,
        EventFiring.ASYNCHRONOUS, EnumSet.of(EventType.CREATED, EventType.EXPIRED)); 
    return cacheManager;
}

Haven't tested it myself, but this should work for you.

Check out this programatic sample with more configuration options from the EhCache repo and the docs part on how to register listeners programatically too.

Aritz
  • 30,971
  • 16
  • 136
  • 217
  • 1
    where is resources(heap/offheap/disk) part? – gstackoverflow Sep 20 '19 at 15:04
  • Updated for your concrete case ;-) – Aritz Sep 20 '19 at 19:38
  • From what packages are these classes? I'm trying to reuse this solution but unfortunately without success. Moreover when I try to use this code overriding `CachingConfigurer.cacheManager()` then I get error `Error creating bean with name 'cacheResolver' ... java.lang.IllegalArgumentException: CacheManager is required` – Iwo Kucharski May 27 '20 at 14:37
  • 1
    How change memoryStoreEvictionPolicy to LFU programatically? – Dmitriy Jul 04 '20 at 13:08
8

Here is my solution

@Bean
CacheManager getCacheManager() {

    CachingProvider provider = Caching.getCachingProvider();
    CacheManager cacheManager = provider.getCacheManager();

    CacheConfigurationBuilder<String, String> configurationBuilder =
            CacheConfigurationBuilder.newCacheConfigurationBuilder(
                    String.class, String.class,
                    ResourcePoolsBuilder.heap(1000)
                                        .offheap(25, MemoryUnit.MB))
                                     .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofHours(3)));

    CacheEventListenerConfigurationBuilder asynchronousListener = CacheEventListenerConfigurationBuilder
            .newEventListenerConfiguration(new CacheEventLogger()
                    , EventType.CREATED, EventType.EXPIRED).unordered().asynchronous();

    //create caches we need
    cacheManager.createCache("productCatalogConfig",
                             Eh107Configuration.fromEhcacheCacheConfiguration(configurationBuilder.withService(asynchronousListener)));

    return cacheManager;
}

equivalent of :

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.ehcache.org/v3"
    xmlns:jsr107="http://www.ehcache.org/v3/jsr107"
    xsi:schemaLocation="
        http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd
        http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">

<cache alias="productCatalogConfig">
    <key-type>java.lang.String</key-type>
    <value-type>java.lang.String</value-type>
    <expiry>
        <ttl unit="seconds">1600</ttl>
    </expiry>

    <listeners>
        <listener>
            <class>com.klarna.config.CacheEventLogger</class>
            <event-firing-mode>ASYNCHRONOUS</event-firing-mode>
            <event-ordering-mode>UNORDERED</event-ordering-mode>
            <events-to-fire-on>CREATED</events-to-fire-on>
            <events-to-fire-on>EXPIRED</events-to-fire-on>
        </listener>
    </listeners>

    <resources>
        <heap unit="entries">1000</heap>
        <offheap unit="MB">25</offheap>
    </resources>
</cache>
Nodirbek Shamsiev
  • 552
  • 1
  • 11
  • 21