Spring Cache简介
2026/1/15大约 3 分钟SpringSpring CacheJava缓存后端
Spring Cache简介
什么是 Spring Cache
Spring Cache 是 Spring 框架提供的缓存抽象层,它不是具体的缓存实现,而是定义了一套缓存操作的标准接口和注解。通过这套抽象,开发者可以使用统一的方式操作不同的缓存实现。
核心优势
1. 声明式缓存
通过注解即可实现缓存,无需编写缓存操作代码。
// 不使用 Spring Cache
public User getUser(Long id) {
String key = "user:" + id;
User user = cache.get(key);
if (user == null) {
user = userRepository.findById(id);
cache.put(key, user);
}
return user;
}
// 使用 Spring Cache
@Cacheable(value = "users", key = "#id")
public User getUser(Long id) {
return userRepository.findById(id);
}2. 与缓存实现解耦
切换缓存实现只需更改配置,无需修改业务代码。
3. 支持 SpEL 表达式
灵活的 Key 生成和条件判断。
快速开始
1. 添加依赖
<!-- Spring Boot Starter Cache -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Caffeine 缓存实现 -->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>2. 启用缓存
@SpringBootApplication
@EnableCaching // 启用缓存
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}3. 配置缓存
# application.yml
spring:
cache:
type: caffeine
caffeine:
spec: maximumSize=10000,expireAfterWrite=10m4. 使用缓存注解
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
// 查询时缓存
@Cacheable(value = "users", key = "#id")
public User getById(Long id) {
return userRepository.findById(id).orElse(null);
}
// 更新时更新缓存
@CachePut(value = "users", key = "#user.id")
public User update(User user) {
return userRepository.save(user);
}
// 删除时清除缓存
@CacheEvict(value = "users", key = "#id")
public void delete(Long id) {
userRepository.deleteById(id);
}
}核心组件
CacheManager
缓存管理器,负责创建和管理 Cache 实例。
public interface CacheManager {
Cache getCache(String name);
Collection<String> getCacheNames();
}常用实现:
| 实现 | 说明 |
|---|---|
| SimpleCacheManager | 简单实现,需手动配置 Cache |
| ConcurrentMapCacheManager | 基于 ConcurrentHashMap |
| CaffeineCacheManager | 基于 Caffeine |
| RedisCacheManager | 基于 Redis |
| EhCacheCacheManager | 基于 Ehcache |
Cache
缓存接口,定义了缓存的基本操作。
public interface Cache {
String getName();
Object getNativeCache();
ValueWrapper get(Object key);
<T> T get(Object key, Class<T> type);
void put(Object key, Object value);
void evict(Object key);
void clear();
}缓存注解
| 注解 | 作用 |
|---|---|
@Cacheable | 查询缓存,不存在则执行方法并缓存结果 |
@CachePut | 执行方法并更新缓存 |
@CacheEvict | 删除缓存 |
@Caching | 组合多个缓存操作 |
@CacheConfig | 类级别的缓存配置 |
工作原理
Spring Cache 基于 AOP 实现,通过代理拦截方法调用:
小结
Spring Cache 提供了统一的缓存抽象,通过注解方式简化缓存操作。它支持多种缓存实现,可以根据需求灵活切换。
面试题预览
常见面试题
- Spring Cache 的核心注解有哪些?
- @Cacheable 和 @CachePut 有什么区别?
- Spring Cache 的工作原理是什么?
