SpringBoot 中 使用Redis定时删除Key缓存

该博客介绍了如何在Spring Boot应用中集成Redis作为缓存。首先,引入了spring-boot-starter-data-redis依赖。然后,创建了一个名为CacheRedisServiceImpl的服务类,包含了获取和设置缓存的方法。通过RedisTemplate的expire方法设置了缓存的过期时间,使用Duration.ofMillis()指定以毫秒为单位的过期时间,确保数据在设定的时间后自动过期。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.导入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2.先创建一个类CacheRedisServiceImpl

根据key取出缓存getRedis

存储数据setRedis

redisTemplate.expire(key,duration);第一个参数key,第二个是 Duration类型,大概是个时间类

Duration.ofMillis()方法,参数是long类型,在里面设置时间,时间一到自动过期

@Service
public class CacheRedisServiceImpl {

    @Autowired
    public RedisTemplate redisTemplate;

    public static long EXPIRE_TIME=240*60*1000;
    

    public Object getRedis(String key) {
        //通过key取出数据
        return redisTemplate.opsForValue().get(key);
    }

    public void setRedis(String key, Object value) {
        //存储key
        redisTemplate.opsForValue().set(key, value);
        //设置过期时间
        Duration duration=Duration.ofMillis(EXPIRE_TIME);
        //设置定时删除
        redisTemplate.expire(key,duration);
    }
}

 

### Spring Boot 中刷新 Redis 缓存的方法 在Spring Boot项目中,为了确保缓存数据的一致性和时效性,提供了一套完整的机制用于管理和操作Redis缓存。当涉及到刷新缓存的操作时,通常有几种方式可以选择。 #### 使用 `@CacheEvict` 注解清除缓存 对于简单的场景,可以直接利用Spring Cache框架提供的`@CacheEvict`注解来标记那些需要触发清空特定命名空间下所有条目或者单个键对应的值的方法[^1]。此注解支持多种参数设置以满足不同的业务需求: - **allEntries**: 设置为true表示清除整个缓存区域内的所有元素; - **beforeInvocation**: 默认情况下是在方法成功执行之后才清理缓存,默认false;设为true则会在调用之前就立即生效。 ```java @Service public class UserService { @CachePut(value = "users", key = "#id") public User updateUser(User user){ // 更新用户的逻辑... return userRepository.save(user); } @CacheEvict(value="users", allEntries=true) public void clearUserCache(){ // 清除所有的用户缓存记录 } } ``` #### 手动控制缓存更新 除了依靠内置的注解外,在某些复杂的应用环境中可能还需要更灵活的手动干预措施。可以通过注入`CacheManager`实例获取到具体的`Cache`对象来进行增删改查等基本操作[^2]。这种方式给予开发者更大的自由度去定制化处理流程。 ```java @Autowired private CacheManager cacheManager; public void refreshCache(String cacheName, String key) { Cache cache = cacheManager.getCache(cacheName); if (cache != null && StringUtils.hasText(key)) { cache.evict(key); // 移除指定key缓存项 } else { log.warn("Failed to find the specified cache or invalid key."); } } ``` #### 定期任务自动刷新策略 考虑到实际应用场景下的性能优化以及维护成本等因素,还可以借助定时调度工具(如Quartz、Spring Task)配合上述两种方案之一定期执行批量重置动作,从而达到自动化运维的目的[^3]。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-task</artifactId> </dependency> ``` ```java @Configuration @EnableScheduling public class ScheduleConfig {} @Component public class CacheRefreshTask { private final static Logger logger = LoggerFactory.getLogger(CacheRefreshTask.class); @Scheduled(cron = "0 0 * * * ?") // 每小时的第一分钟运行一次 public void execute() { try { // 调用相应的服务层接口完成具体业务逻辑 userService.clearUserCache(); logger.info("Successfully refreshed caches at {}", LocalDateTime.now()); } catch (Exception e) { logger.error("Error occurred while refreshing caches.", e); } } } ``` 通过这些手段可以在不同层次上有效地管理着应用程序内部所使用的各种类型的缓存资源,并且能够很好地适应于各类复杂的分布式系统架构之中。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qingqingyyds

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值