java - ehcache3 - 为什么缓存不会过期?

标签 java hibernate maven spring-boot ehcache-3

我想缓存一些我的 dao 查询。它可以工作,但缓存不会过期。我做错了什么?

我的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>

在 application.properties 中我有条目:

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

在 pom 中:

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

我的查询:

@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;
}

我预计 5 秒后会过期,但在此时间(或更长时间)之后查询仍会被缓存。我做错了什么?

最佳答案

如果这对其他人有帮助,就我而言,我缺少的是 spring-boot-starter-cache 依赖项。如果没有这种依赖关系,缓存可以工作,但不会发生过期,因为没有 spring-boot 的自定义,spring 可能使用 ConcurrentHashMap 而不是 ehcache 进行缓存,如本文 caching guide 中所述。 。我需要添加的所有 gradle 依赖项如下:

    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

可以在 github 上找到使用 ehcache 成功缓存条目并使条目过期的示例应用程序。

关于java - ehcache3 - 为什么缓存不会过期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55528443/

相关文章:

spring - 如何防止hibernate5在jackson序列化json对象时延迟获取?

java - Maven 自定义依赖类型

java - PersistenceUtil.isLoaded 是什么意思?

java - REST:以 CSV 形式返回对象列表,而不写入磁盘(java spring)

java - 用taglib、jsp、JS封装menuItem?

java - SQL 命令未正确结束更新

java - 使用 Hibernate Annotations 映射枚举类型

java - 替换为 Hibernate 实体

java - 即使没有注释,Junit 5也会在maven构建中执行测试

java - Maven surefire environmentVariables 在一台机器上不起作用