java - Spring Boot 2.0 Hibernate 5 EhCache 3 与 JCache
问题描述
我正在尝试使用 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 类的配置方式:
@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 查询)。
这是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,因为当我使其无效时(例如,通过删除堆标签)我得到一个错误。
解决方案
我想我找到了问题的原因 - 您没有指定ehcache.xml
文件的位置:
spring:
jpa:
properties:
hibernate:
javax.cache:
provider: org.ehcache.jsr107.EhcacheCachingProvider
uri: classpath:ehcache.xml
cache:
use_second_level_cache: true
region.factory_class: jcache
use_query_cache: true
在这种情况下,Hibernate 使用默认配置创建缓存。我的演示项目日志中的一个片段:
17:15:19 WARN [main] org.hibernate.orm.cache: HHH90001006: Missing cache[user] was created on-the-fly. The created cache will use a provider-specific default configuration: make sure you defined one. You can disable this warning by setting 'hibernate.javax.cache.missing_cache_strategy' to 'create'.
推荐阅读
- c# - 在 .net 核心中分离业务域
- sql - PostgreSQL - 正则表达式约束,以便 varchar 仅包含数字
- amazon-web-services - 如何在 MediaLive 和 MediaStore 上实现低延迟
- ruby-on-rails - Shopify RecurringApplicationCharge 的确认 URL 为 nil
- javascript - 在 nodejs 和 typescript 中使用 dotenv 模块
- google-bigquery - 在 BigQuery 中回填预定查询
- sql - 对于字典搜索,是否有更好的交叉连接替代方法?
- angular - MSAL (Angular) 弹出式登录
- javascript - 如何在资金管理器应用程序中存储交易日期?
- spring-cloud - 如何在 Java 配置中添加自定义 Spring Cloud Gateway 过滤器?