基础与注解用法
2025/9/17大约 3 分钟
Spring Cache 基础与注解用法
前置知识
建议你已掌握 Spring Boot 基础、Java 注解、常见缓存概念。
目录
Spring Cache 简介与应用场景
Spring Cache 是 Spring 提供的统一缓存抽象,支持多种缓存实现(如 Caffeine、EhCache、Redis)。
- 通过注解方式实现方法级缓存,简化开发
- 支持本地缓存、分布式缓存
- 适用于热点数据、接口结果、配置参数等场景
常见应用场景:
- 数据库查询结果缓存
- 远程接口调用结果缓存
- 配置、字典、权限等静态数据缓存
核心注解与用法
@Cacheable
:方法结果缓存,优先查缓存,无则执行方法并缓存结果@CachePut
:每次执行方法并更新缓存@CacheEvict
:清除缓存@Caching
:组合多个缓存操作
注解用法示例
// 查询时缓存
@Cacheable(value = "user", key = "#id")
public User getUserById(Long id) { ... }
// 更新时刷新缓存
@CachePut(value = "user", key = "#user.id")
public User updateUser(User user) { ... }
// 删除时清除缓存
@CacheEvict(value = "user", key = "#id")
public void deleteUser(Long id) { ... }
// 组合操作
@Caching(
cacheable = @Cacheable(value = "user", key = "#id"),
evict = @CacheEvict(value = "user", key = "#id", condition = "#result == null")
)
public User findOrEvict(Long id) { ... }
基本配置与依赖
1. Maven 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- 选择具体实现,如 Caffeine、Redis 等 -->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.1.8</version>
</dependency>
2. 启用缓存
@SpringBootApplication
@EnableCaching // 启用 Spring Cache
public class App { ... }
3. application.yml 示例
spring:
cache:
type: caffeine # 指定缓存实现
cache-names: user,product
caffeine:
spec: maximumSize=1000,expireAfterWrite=10m # 最大1000条,写入10分钟过期
缓存原理与流程
- 方法调用前,先查缓存(key 由 value+key 表达式组成)
- 若命中缓存,直接返回结果
- 若未命中,执行方法并将结果存入缓存
- 支持条件缓存、同步刷新、失效清理等
缓存流程图
graph TD;
A[方法调用] --> B{缓存命中?};
B -- 是 --> C[直接返回缓存结果];
B -- 否 --> D[执行方法];
D --> E[结果存入缓存];
E --> F[返回结果];
代码示例
UserService.java
package com.example.cache;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
@Data
class User {
private Long id;
private String name;
}
@Slf4j
@Service
public class UserService {
// 查询时缓存
@Cacheable(value = "user", key = "#id")
public User getUserById(Long id) {
log.info("查询数据库: {}", id);
// 模拟数据库查询
User user = new User();
user.setId(id);
user.setName("用户" + id);
return user;
}
// 更新时刷新缓存
@CachePut(value = "user", key = "#user.id")
public User updateUser(User user) {
log.info("更新数据库: {}", user.getId());
// ...更新逻辑
return user;
}
// 删除时清除缓存
@CacheEvict(value = "user", key = "#id")
public void deleteUser(Long id) {
log.info("删除用户: {}", id);
// ...删除逻辑
}
}
常见问题与小结
常见问题
- 缓存未生效:检查 @EnableCaching、注解位置、key 表达式
- 缓存穿透:方法返回 null 也会缓存,建议 condition/ unless 控制
- 缓存更新不及时:合理使用 @CachePut/@CacheEvict
- 多实例缓存不一致:推荐用 Redis 等分布式缓存
- Spring Cache 注解简化了缓存开发,适合方法级缓存
- 推荐结合具体实现(如 Caffeine/Redis)灵活配置
- 后续将介绍常用缓存实现、失效策略与实战技巧
本文为 Spring Cache 系列教程第一篇,后续将介绍 Caffeine/Redis 配置、缓存失效与高级用法,敬请期待!