RedisLockRenewal.java 1.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
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);
    }
}