一、核心架构图解
二、核心组件解析
1. 缓存注解
@Cacheable("users") // 缓存读取
public User getUserById(Long id) { ... }
@CachePut(value = "users", key = "#user.id") // 缓存更新
public User updateUser(User user) { ... }
@CacheEvict(value = "users", allEntries = true) // 缓存清除
public void refreshUsers() { ... }
2. 缓存管理器
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("users", "products");
}
}
3. 缓存实现适配
三、工作流程解析
四、关键技术特性
缓存功能矩阵
特性 | 实现方式 | 示例 |
---|---|---|
条件缓存 | @Cacheable(condition) | condition="#id > 1000" |
键生成策略 | keyGenerator | 自定义KeyGenerator实现 |
缓存同步 | @Cacheable(sync=true) | 防止缓存击穿 |
多缓存操作 | @Caching | 组合多个缓存操作 |
五、最佳实践示例
1. 复合缓存操作
@Caching(
cacheable = {
@Cacheable(value = "user", key = "#id")
},
put = {
@CachePut(value = "user", key = "#result.username")
}
)
public User getUserWithCache(Long id) { ... }
2. 自定义TTL配置(Redis示例)
@Bean
public RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer() {
return builder -> builder
.withCacheConfiguration("users",
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(30))
.disableCachingNullValues()
);
}
3. 缓存监控配置
# application.properties
management.endpoint.caches.enabled=true
management.endpoints.web.exposure.include=caches
六、缓存策略选择指南
Spring的缓存抽象机制通过统一API实现了:
- 多缓存实现的无缝切换
- 声明式缓存管理
- 细粒度缓存控制
- 与Spring生态的深度集成
实际应用中需注意:
- 缓存一致性维护
- 缓存雪崩/穿透预防
- 缓存监控与统计
- 适当的缓存失效策略