Spring Cache是Spring框架提供的缓存抽象层,通过注解和自动化配置,简化应用中对缓存的操作,支持多种缓存实现(如Redis、Ehcache、Caffeine)。
注解 | 作用 | 常用参数 | 示例 |
---|---|---|---|
@EnableCaching | 开启缓存注解功能,通常加在启动类上 | ||
@Cacheable | 方法结果缓存。在方法执行前先查询缓存中是否有数据,如果有数据则直接返回缓存数据;如果没有缓存数据,调用方法并将方法返回值放到缓存中 | value(缓存名)、key(键)、condition(条件) | 缓存数据库查询结果 |
@CachePut | 更新缓存,将方法的返回值放到缓存中 | value(缓存名)、key(键)、condition(条件) | 数据更新后刷新缓存 |
@CacheEvict | 删除缓存,将一条或多条数据从缓存中删除 | allEntries(清空所有键)、beforeInvocation(执行前删除) | 数据清除时删除缓存 |
1. @Cacheable:
作用:标记方法的结果需要被缓存。当方法被调用时,先检查缓存是否存在对应键值,若存在则直接返回缓存值,否则执行方法并将结果存入缓存。
使用场景:查询操作(如数据库查询、复杂计算等)。
示例:
@Cacheable(value = "userCache", key = "#userId", condition = "#userId != null")
public User getUserById(Long userId) {
return userRepository.findById(userId).orElse(null);
}
2. @CachePut:
作用:更新缓存。无论缓存是否存在,都会执行方法,并将结果更新到缓存中。
适用场景:新增或更新操作(如更新用户信息后同步缓存)。
示例:
@CachePut(value = "userCache", key = "#user.id")
public User updateUser(User user) {
return userRepository.save(user);
}
3. @CacheEvict
作用:删除缓存。根据条件清除指定键或整个缓存区的数据。
适用场景:删除操作(如用户删除后清理缓存)。
示例:
@CacheEvict(value = "userCache", key = "#userId")
public void deleteUser(Long userId) {
userRepository.deleteById(userId);
}
// 清空整个缓存区
@CacheEvict(value = "userCache", allEntries = true)
public void clearAllUserCache() {}
添加依赖:
org.springframework.boot
spring-boot-starter-cache
org.springframework.boot
spring-boot-starter-data-redis
配置缓存类型与Redis:
# application.properties
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379
# 可选:设置缓存过期时间(单位:毫秒)
spring.cache.redis.time-to-live=60000
启用缓存:在启动类添加@EnableCaching
@SpringBootApplication
@EnableCaching
public class MyApp { ... }
在Service层使用注解:
// 仅当参数id>10时缓存
@Cacheable(value = "users", condition = "#id > 10")
// 结果不为null时缓存
@Cacheable(value = "users", unless = "#result == null")
自定义缓存键(SpEL表达式)
@Cacheable(value = "orders", key = "#userId + ':' + #status")
public List getOrdersByUserAndStatus(Long userId, String status) { ... }
条件缓存(condition和unless)
// 仅当参数id>10时缓存
@Cacheable(value = "users", condition = "#id > 10")
// 结果不为null时缓存
@Cacheable(value = "users", unless = "#result == null")
Spring Cache通过简化缓存逻辑与代码解耦,显著提升了开发效率。结合Redis等高性能缓存工具,能够轻松应对高并发场景。