基于redis分布式锁解决定时任务重复问题

在看代码之前请先看优化篇:基于Redis的Setnx实现分布式锁_p&f°的博客-CSDN博客

1、在启动了上加 @EnableScheduling 注解

@SpringBootApplication
@MapperScan("com.xpf.distributelock.dao")
@EnableScheduling
public class DistributeLockApplication {

    public static void main(String[] args) {
        SpringApplication.run(DistributeLockApplication.class, args);
    }

}

2、 写一个server类

import com.xpf.distributelock.until.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * @auther xpf
 * @date 2022/6/10 21:24
 * @description 定时任务
 */
@Slf4j
@Service
public class SchedulerService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(cron = "0/5 * * * * ?")
    public void sendSms(){
        try(RedisLock redisLock = new RedisLock("autoSms", 30, redisTemplate)){
            if(redisLock.getLock()){
                log.info("向我开炮。。。。🤺");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

以防急用,没看前一篇文章,把 RedisLock 也再贴一下

import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.core.types.Expiration;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @auther xpf
 * @date 2022/6/10 11:15
 * @description 封装redis分布式锁
 */
public class RedisLock implements AutoCloseable {

    private String key;
    private String value;
    private int expiration;
    private RedisTemplate redisTemplate;

    public RedisLock(String key, int expiration, RedisTemplate redisTemplate) {
        this.key = key;
        this.value = UUID.randomUUID().toString();
        this.expiration = expiration;
        this.redisTemplate = redisTemplate;
    }

    public Boolean getLock(){
        RedisCallback<Boolean> redisCallback = connection -> {
            //设置NX
            RedisStringCommands.SetOption setOption = RedisStringCommands.SetOption.ifAbsent();
            //设置过期时间
            Expiration expiration1 = Expiration.seconds(expiration);
            //序列化key
            byte[] redisKey = redisTemplate.getKeySerializer().serialize(key);
            //序列化value
            byte[] redisValue = redisTemplate.getValueSerializer().serialize(value);

            //执行setnx操作
            Boolean result = connection.set(redisKey, redisValue, expiration1, setOption);
            return result;
        };

        //获取分布式锁
        Boolean lock = (Boolean) redisTemplate.execute(redisCallback);
        return lock;
    }

    public Boolean unLock(){
        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        RedisScript<Boolean> redisScript = RedisScript.of(script, Boolean.class);
        List<String> keys = Arrays.asList(key);

        Boolean result = (Boolean) redisTemplate.execute(redisScript, keys, value);
        return result;
    }

    /**
     * jdk1.7新特性:实现 AutoCloseable ,就可以不用在finally里面写释放锁的代码了
     * @throws Exception
     */
    @Override
    public void close() throws Exception {
        unLock();
    }
}

3、启动两个Application模拟分布式服务,查看定时任务执行情况,发现是顺序执行的,结果截图如下

8080执行情况

8081执行情况

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值