Spring Cache与Redis集成实现自动缓存

使用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作为缓存后端提供了高性能和持久化能力,适合生产环境使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值