Search code examples
javaspringspring-bootehcachespring-cache

timetoliveseconds ehcache spring boot config is not working


Below is my ehcache Config file

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="ehcache.xsd"
    updateCheck="true"
    monitoring="autodetect"
    dynamicConfig="true">

    <diskStore path="java.io.tmpdir" />



    <cache name="trans"
        maxEntriesLocalHeap="10000"
        maxEntriesLocalDisk="1000"
        eternal="false"
        diskSpoolBufferSizeMB="20"
        timeToIdleSeconds="0"
        timeToLiveSeconds="6"
        memoryStoreEvictionPolicy="LFU"
        transactionalMode="off">
        <persistence strategy="localTempSwap" />
    </cache>    
</ehcache>

All Spring annotation and configurations are working correctly

@Component
@CacheConfig(cacheNames = {"trans" })
public class MyTransService {

    private List<Trans> list;

    @Autowired
    private EhCacheCacheManager manage;

    @PostConstruct
    public void setup() {
        list = new ArrayList<>();
    }

    @CachePut
    public void addTransaction(Trans trans) {
        this.list.add(trans);
    }

    @CacheEvict(allEntries = true)
    public void deleteAll() {
        this.list.clear();
    }    
}

But the cache is not getting clear after timetoliveseconds.

Can someone help me whats wrong in my config.

Below page says that it's bug , but not sure how to fix this ?
I am using spring-boot-starter-cache-2.0.3 version

https://github.com/ehcache/ehcache-jcache/issues/26

there are some similar questions but not providing any solutions


Solution

  • Was able to resolve this using ehcache-JSR-107 wrapper. Below is java config

    @Component
    public class CachingSetup implements JCacheManagerCustomizer {
    
         @Override
         public void customize(CacheManager cacheManager)
         {
           cacheManager.createCache("trans", new MutableConfiguration<>()
             .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(SECONDS, 10)))
             .setStoreByValue(false)
             .setStatisticsEnabled(true));
         }
    }
    

    Pom

    <dependencies>
            <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-cache</artifactId> <!--Starter for using Spring Framework's caching support-->
            </dependency>           
            <dependency>
              <groupId>javax.cache</groupId> <!-- JSR-107 API-->
              <artifactId>cache-api</artifactId>
            </dependency>
            <dependency>
              <groupId>org.ehcache</groupId>
              <artifactId>ehcache</artifactId>
              <version>3.0.0</version>
            </dependency>
        </dependencies>