我正在尝试使用EhCache作为Hibernate的二级缓存,但TTL无法正常工作。
以下是我的依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jcache</artifactId>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>
这是我的YAML配置:
spring:
jpa:
show-sql: true
properties:
hibernate:
dialect: Dialect
cache:
use_second_level_cache: true
region.factory_class: org.hibernate.cache.jcache.JCacheRegionFactory
use_query_cache: true
cache:
jcache:
config: classpath:ehcache.xml
这是我的实体类如何配置的:
@Entity
@javax.persistence.Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class PersonEntity {
//
}
该实体的JpaRepository:
public interface PersonRepository extends JpaRepository<PersonEntity, Integer> {
@org.springframework.data.jpa.repository.QueryHints({
@javax.persistence.QueryHint(name = "org.hibernate.cacheable", value = "true")
})
List<PersonEntity> findByName(String name);
}
我已将缓存配置为在2秒钟后过期,但调用findByName
仍然使用缓存(第一个SQL查询之后没有打印出任何SQL查询)。
这是ehcache.xml
文件:
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://www.ehcache.org/v3">
<cache-template name="simple">
<expiry>
<ttl>2</ttl>
</expiry>
<heap>100</heap>
</cache-template>
<cache alias="com.sample.PersonEntity" uses-template="simple"/>
</config>
编辑:
我已经进行了一些调试。我在org.ehcache.jsr107.ExpiryPolicyToEhcacheExpiry
中添加了一个断点:
javax.cache.expiry.Duration duration = this.expiryPolicy.getExpiryForCreation();
出于某种原因,这个持续时间是无限的。那么可能是配置没有设置好?我知道xml被读取了,因为当我使其无效(例如删除堆标签)时,会出现错误。
GET localhost:8080/users?name=smith
。用户的TTL为1分钟。希望这可以帮助... - Cepr0cache.jcache.config=classpath:ehcache.xml
是关于什么的。请花点时间回复。我想知道上述内容与hibernate.javax.cache.uri=classpath:ehcache.xml
之间的区别。 - samshers