package com.kwan.springbootkwan.schedule; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @Component public class RedisLockRenewal { private final StringRedisTemplate redisTemplate; /** * 定时任务线程池 */ private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); @Autowired public RedisLockRenewal(StringRedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } public void scheduleRenewal(String lockKey, long renewalIntervalMillis, long lockExpireMillis) { scheduler.scheduleAtFixedRate(() -> { try { // 续期操作:设置新的过期时间 redisTemplate.expire(lockKey, lockExpireMillis, TimeUnit.MILLISECONDS); } catch (Exception e) { // 处理续期失败的情况,可以记录日志或采取其他操作 e.printStackTrace(); } }, renewalIntervalMillis, renewalIntervalMillis, TimeUnit.MILLISECONDS); } }