简体   繁体   中英

ehcache3 - why cache doesn't expire?

I want to cache a few of my dao queries. And it works, but cache doesn't expire. What I'm doing wrong?

My ehcache.xml:

<config xmlns='http://www.ehcache.org/v3'
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        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="test">
    <key-type>java.lang.String</key-type>
    <value-type>xxx.model.SignalValueType</value-type>
        <expiry>
            <ttl unit="seconds">5</ttl>
        </expiry>

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

In application.properties I have entry:

spring.cache.jcache.config=classpath:ehcache.xml

In pom:

<dependency>
    <groupId>javax.cache</groupId>
    <artifactId>cache-api</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

And my query:

@Cacheable(value = "test", key = "#code")
@Override
public SignalValueType getSignalValueType(String code) {         
  SignalValueType signalType = (SignalValueType) sf.getCurrentSession()
.createQuery("FROM SignalValueType svt WHERE svt.code = :code").setParameter("code", code)
.uniqueResult();

 return signalType;
}

I expect 5 seconds expiring, but after this time (and longer) query is still cached. What I'm doing wrong?

不应该是ehcache而不是jcache

spring.cache.ehcache.config= {ehcache config location}

In case this helps anyone else, in my case what I was missing was the spring-boot-starter-cache dependency. Without that dependency, caching was working but no expiration was happening as without the customizations from spring-boot , spring was probably caching using a ConcurrentHashMap instead of ehcache , as mentioned in this caching guide . All the gradle dependencies I needed to add are below:

    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-cache'
    implementation group: 'org.ehcache', name: 'ehcache'
    implementation group: 'javax.cache', name: 'cache-api'

    implementation group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.1' // To read XML config
    implementation group: 'com.sun.xml.bind', name: 'jaxb-impl', version: '2.3.6' // To read XML config

A sample application that successfully caches and expires entries using ehcache can be found on github

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM