使用Spring Cache与Redis集成实现自动缓存
Spring Cache抽象提供了一种声明式的方式来管理缓存,结合Redis作为缓存存储,可以通过简单的注解实现自动缓存操作。
配置Redis作为缓存管理器
确保项目中包含Spring Boot Redis Starter依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
在application.properties中配置Redis连接:
spring.redis.host=localhost
spring.redis.port=6379
配置RedisCacheManager:
@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(RedisCacheConfiguration.defaultCacheConfig())
.build();
}
}
使用缓存注解实现自动缓存
Spring提供以下核心缓存注解:
@Cacheable - 方法结果将被缓存:
@Cacheable(value = "users", key = "#id")
public User findUserById(Long id) {
// 数据库查询逻辑
return userRepository.findById(id).orElse(null);
}
@CachePut - 更新缓存内容:
@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
// 更新数据库
return userRepository.save(user);
}
@CacheEvict - 清除缓存:
@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
自定义缓存行为
可以配置缓存TTL(过期时间):
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(30));
return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(config)
.build();
}
使用SpEL表达式定义复杂缓存键:
@Cacheable(value = "orders", key = "#userId + '_' + #orderType")
public List<Order> findOrders(Long userId, String orderType) {
// 查询逻辑
}
条件缓存
通过condition参数实现条件缓存:
@Cacheable(value = "products", key = "#id", condition = "#id > 10")
public Product findProduct(Long id) {
// 查询逻辑
}
使用unless排除特定返回值:
@Cacheable(value = "products", key = "#id", unless = "#result == null")
public Product findProduct(Long id) {
// 查询逻辑
}
缓存同步模式
@Cacheable支持sync属性,在多线程环境下防止缓存击穿:
@Cacheable(value = "hotProducts", key = "#id", sync = true)
public Product getHotProduct(Long id) {
// 查询逻辑
}
这种声明式缓存方式显著减少了样板代码,同时保持了代码的整洁性和可维护性。Redis作为缓存后端提供了高性能和持久化能力,适合生产环境使用。


343

被折叠的 条评论
为什么被折叠?



