如何在Spring Boot 3中使用Ehcache 3实现二级缓存?依赖冲突求助
Spring Boot 3 + Ehcache 3 + Hibernate 6 二级缓存整合方案
一、修正依赖配置(Maven)
Spring Boot 3 基于 Jakarta EE,Ehcache 3.10+ 已支持 Jakarta 规范,需引入适配版本避免 Javax/Jakarta 冲突:
<dependencies> <!-- Spring Boot JPA Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- Ehcache 3 核心依赖(支持 Jakarta) --> <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> <version>3.10.8</version> </dependency> <!-- Hibernate 6 JCache 适配依赖 --> <dependency> <groupId>org.hibernate.orm</groupId> <artifactId>hibernate-jcache</artifactId> <version>6.4.4.Final</version> <!-- 与 Spring Boot 3.2.x 适配 --> <scope>runtime</scope> </dependency> </dependencies>
若依赖无法下载,检查 Maven 镜像源是否配置正确(如阿里云镜像),排除私有仓库限制。
二、配置 Hibernate 二级缓存
在 application.yml(或 application.properties)中添加缓存配置:
spring: jpa: properties: hibernate: cache: use_second_level_cache: true use_query_cache: true region.factory_class: org.hibernate.cache.jcache.JCacheRegionFactory jakarta: persistence: sharedCache: mode: ENABLE_SELECTIVE
三、编写 Ehcache 3 配置文件
在 src/main/resources 下创建 ehcache.xml,定义缓存规则:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.ehcache.org/v3" xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd"> <!-- 默认缓存模板 --> <cache-template name="default"> <key-type>java.lang.Object</key-type> <value-type>java.lang.Object</value-type> <expiry> <ttl unit="minutes">30</ttl> </expiry> <resources> <heap unit="entries">1000</heap> <offheap unit="MB">100</offheap> </resources> </cache-template> <!-- 实体类对应的缓存区域 --> <cache alias="com.example.entity.User" uses-template="default"/> <!-- 可添加更多实体缓存配置 --> </config>
四、启用实体类缓存
在需要缓存的 JPA 实体类上添加 Hibernate 缓存注解:
import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; @Entity @Table(name = "user") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "com.example.entity.User") public class User { @Id private Long id; private String username; // 省略 getter/setter }
关键说明
- 必须使用 ≥3.10 版本的 Ehcache,这是支持 Jakarta 规范的最低版本,可解决 Javax/Jakarta 依赖冲突。
- Hibernate 6 的
hibernate-jcache依赖 GroupId 为org.hibernate.orm,而非旧版的org.hibernate。 - 若仍有依赖无法获取问题,清理本地 Maven 仓库后重新拉取,或检查项目依赖管理是否锁定了冲突版本。
内容的提问来源于stack exchange,提问作者HyperX Pro
相关产品推荐
相关产品推荐

