You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何确保Spring Boot应用中Ehcache二级缓存已启用并验证生效

如何确保Spring Boot中Ehcache+Spring Data JPA二级缓存启用并验证其工作

一、确保二级缓存启用的核心检查点

1. 依赖配置

现有依赖缺少Spring缓存启动器,且Hibernate-Ehcache使用了预览版,需调整:

  • 添加Spring Cache Starter(Spring缓存抽象的核心依赖):
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    
  • 替换Hibernate-Ehcache为稳定版(与Spring Boot版本匹配,例如Spring Boot 3.2.x对应Hibernate 6.4.x):
    <dependency>
        <groupId>org.hibernate.orm</groupId>
        <artifactId>hibernate-ehcache</artifactId>
        <version>6.4.4.Final</version>
    </dependency>
    

2. 配置文件修正

现有配置中Hibernate缓存区域工厂类适配的是旧版本,需调整为Hibernate 6.x兼容的类,并补充必要配置:

# Hibernate二级缓存配置
hibernate.cache.use_second_level_cache=true
# Hibernate 6.x需使用JCache实现的区域工厂
hibernate.cache.region.factory_class=org.hibernate.cache.jcache.JCacheRegionFactory
hibernate.cache.use_query_cache=true

# Spring缓存配置
spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:ehcache.xml

同时需确保ehcache.xml存在于src/main/resources下,示例配置如下(需替换为你的实体包路径):

<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">

    <!-- Hibernate二级缓存区域(对应Book实体的缓存) -->
    <cache alias="com.yourpackage.Book">
        <key-type>java.lang.Long</key-type>
        <value-type>com.yourpackage.Book</value-type>
        <expiry>
            <ttl unit="minutes">10</ttl>
        </expiry>
        <heap unit="entries">100</heap>
    </cache>

    <!-- Spring缓存区域(对应@Cacheable("book")的配置) -->
    <cache alias="book">
        <key-type>java.lang.Long</key-type>
        <value-type>com.yourpackage.Book</value-type>
        <expiry>
            <ttl unit="minutes">10</ttl>
        </expiry>
        <heap unit="entries">100</heap>
    </cache>
</config>

3. 实体与Repository配置

  • 实体类:你的Book实体已添加@org.hibernate.annotations.Cache,这是启用Hibernate二级缓存的关键,建议补充指定缓存区域以便统一配置:
    @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "book")
    
  • Repository方法:
    • 若要启用Hibernate查询缓存,需在自定义查询方法上添加@QueryHints:
      @QueryHints({@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true")})
      @Query(value = "SELECT b FROM Book b JOIN FETCH b.author a WHERE b.id = :id")
      Optional<Book> fetchById(@Param("id") Long id);
      
    • 注意:你添加的@Cacheable是Spring缓存抽象的注解,与Hibernate二级缓存是独立的两层缓存,可根据需求选择使用其中一种或同时使用。

二、验证缓存正常工作的方法

1. 日志验证

开启SQL和缓存日志,通过日志判断缓存是否命中:

# 打印SQL语句
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

# 开启缓存日志
logging.level.org.hibernate.cache=DEBUG
logging.level.org.springframework.cache=DEBUG
  • 首次调用fetchById或findById:控制台会打印SQL,同时日志显示实体被加入二级缓存(Hibernate)或Spring缓存。
  • 二次及后续调用:若缓存生效,控制台不会打印SQL,日志会显示缓存命中的信息(如Cache hit或Cache entry found)。

2. 直接检查缓存内容

注入缓存管理器,在代码中直接查询缓存数据:

@Service
public class CacheCheckService {
    @Autowired
    private javax.cache.CacheManager jcacheManager;
    @Autowired
    private org.springframework.cache.CacheManager cacheManager;

    public void checkBookCache(Long bookId) {
        // 检查Hibernate二级缓存(区域名为指定的region)
        javax.cache.Cache<Long, Book> hibernateCache = jcacheManager.getCache("book", Long.class, Book.class);
        if (hibernateCache != null) {
            Book book = hibernateCache.get(bookId);
            System.out.println("Hibernate二级缓存数据:" + book);
        }

        // 检查Spring缓存
        org.springframework.cache.Cache springCache = cacheManager.getCache("book");
        if (springCache != null) {
            Book book = springCache.get(bookId, Book.class);
            System.out.println("Spring缓存数据:" + book);
        }
    }
}

3. 性能对比测试

多次调用同一查询方法,统计响应时间:

  • 首次调用因查询数据库,响应时间较长;
  • 后续调用若命中缓存,响应时间会显著缩短,以此验证缓存生效。

内容的提问来源于stack exchange,提问作者Xai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 09:17:04