Spring Boot 3 本地缓存(Caffeine)配置实践

TL;DR:Spring Boot 3 里声明式本地缓存 = spring-boot-starter-cache + caffeine 两个依赖, @EnableCaching 打开代理,yml 里配 spec。 多实例部署时务必想清楚缓存一致性策略,本地缓存不是 Redis 的免费午餐。

依赖:两行搞定

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
</dependency>

Boot 的自动检测到 classpath 上有 Caffeine 且无 Redis 等竞争时, CacheManager 直接装配 CaffeineCacheManager,零 Java 配置也能跑。

开启注解缓存

java
@SpringBootApplication
@EnableCaching   // 少了这个,@Cacheable 全部静默失效——第一坑
public class App { }

application.yml:全局 spec 与按缓存名覆盖

yaml
spring:
  cache:
    type: caffeine
    cache-names: user, dict
    caffeine:
      spec: maximumSize=10000,expireAfterWrite=10m,recordStats

需要不同缓存不同策略(dict 一天不过期、user 五分钟)时,yml 的单一 spec 就不够了, 上代码配置:

java
@Configuration
public class CacheConfig {

    @Bean
    public CacheManager cacheManager() {
        // 每个 cache 独立策略:直接用 Caffeine 构建后包装成 Spring Cache
        Cache userCache = new CaffeineCache("user",
                Caffeine.newBuilder()
                        .maximumSize(50_000)
                        .expireAfterWrite(Duration.ofMinutes(5))
                        .recordStats()
                        .build());

        Cache dictCache = new CaffeineCache("dict",
                Caffeine.newBuilder()
                        .maximumSize(1_000)
                        .expireAfterWrite(Duration.ofHours(24))
                        .build());

        return new SimpleCacheManager(List.of(userCache, dictCache));
    }
}

注解使用与三个高频坑

java
@Service
public class UserService {

    @Cacheable(cacheNames = "user", key = "#id",
               unless = "#result == null")      // null 不缓存,防穿透
    public User getById(Long id) {
        return userMapper.selectById(id);
    }

    @CachePut(cacheNames = "user", key = "#user.id")   // 更新后回填
    public User update(User user) {
        userMapper.updateById(user);
        return user;
    }

    @CacheEvict(cacheNames = {"user", "dict"}, allEntries = true)
    public void clearAll() { }
}
坑现象原因/解法
同类内部调用 缓存完全不生效 绕过了代理。拆到另一个 Bean,或注入自身代理
缓存 null / 异常 击穿或脏数据 unless="#result == null";异常默认不入缓存
key 冲突 不同方法串数据 同 cacheName 下 key 全局唯一,不同方法用不同 cacheName 隔开

多实例下的一致性

  • 本地缓存每个 JVM 一份,写操作只清了自己的——其他实例只能等过期
  • 可接受秒级不一致:把 expireAfterWrite 调短即可,架构最简单
  • 需要主动失效:广播失效消息(Redis pub/sub、MQ),收到后 cacheManager.getCache("user").evict(id)
  • 热点数据 + 强一致诉求:本地缓存只做 L1,L2 用 Redis(Caffeine + Redis 两级),别让 L1 活过 1 分钟

命中率观测

recordStats 打开后,配合 actuator 直接暴露指标:

bash
# build.gradle / pom 加 spring-boot-starter-actuator 后
curl http://localhost:8080/actuator/metrics/cache.get.sum
curl http://localhost:8080/actuator/metrics/cache.invocations?tag=result:hit

小结

  • starter-cache + caffeine + @EnableCaching,三件套缺一即失效
  • 多策略用代码配置 CaffeineCacheManager,别指望单一 yml spec
  • 先定一致性策略再上本地缓存:短过期 < 广播失效 < 两级缓存