使用shedlock实现分布式互斥执行

前言

前序章节:springboot基础(82):分布式定时任务解决方案shedlock

如果你不清楚shedlock,建议先阅读前序章节,再来查看本文。

如果我们不在spring环境下,如何使用shedlock实现分布式互斥执行?

我们可以使用shedlock为我们提供的DefaultLockingTaskExecutor来实现手动调用。

示例

void executeWithLock(@NonNull Runnable var1, @NonNull LockConfiguration var2)

java 复制代码
  @GetMapping("/testRunnable")
    public R testRunnable(HttpServletRequest request) {
        log.info("进入方法");
        String name = request.getParameter("name");
        LockingTaskExecutor executor = new DefaultLockingTaskExecutor(lockProvider);
        Instant now = Instant.now();
        try {
            executor.executeWithLock(new Runnable() {
                @Override
                public void run() {
                    log.info("执行");
                    helloService.helloCn(name);
                }
            }, new LockConfiguration(now, "testRunnable", Duration.ofSeconds(30), Duration.ofSeconds(5)));
            log.info("end");
            return R.ok("success", null);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return R.fail("fail");
    }

LockingTaskExecutor.TaskResult executeWithLock(@NonNull LockingTaskExecutor.TaskWithResult task, @NonNull LockConfiguration lockConfig)

利用此API,我们可以让一个方法不能在一个时间只能有一次实例在执行,排斥调用者,且其它调用者的调用失败,这是与分布式锁不一样的地方。

java 复制代码
 @GetMapping("/testTaskWithResult")
    public R testTaskWithResult(HttpServletRequest request) {
        log.info("进入方法");
        String name = request.getParameter("name");
        LockingTaskExecutor executor = new DefaultLockingTaskExecutor(lockProvider);
        Instant now = Instant.now();
        try {
            LockingTaskExecutor.TaskResult taskResult = executor.executeWithLock(new LockingTaskExecutor.TaskWithResult() {
                @Override
                public Object call() throws Throwable {
                    log.info("执行");
                    return helloService.helloCn(name);
                }
            }, new LockConfiguration(now, "testTaskWithResult", Duration.ofSeconds(30), Duration.ofSeconds(5)));
            boolean flag = taskResult.wasExecuted();
            log.info("end");
            return R.ok("任务是否被执行:" + flag, taskResult.getResult());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return R.fail("fail");
    }

传送门

https://github.com/lukas-krecan/ShedLock

相关推荐
{⌐■_■}10 小时前
【Kafka】登录日志处理的三次阶梯式优化实践:从同步写入到Kafka多分区批处理
数据库·分布式·mysql·kafka·go
qq_5298353510 小时前
RabbitMQ的消息可靠传输
分布式·rabbitmq
CodeWithMe10 小时前
【Note】《Kafka: The Definitive Guide》 第九章:Kafka 管理与运维实战
运维·分布式·kafka
sql2008help11 小时前
1-Kafka介绍及常见应用场景
分布式·kafka
何苏三月15 小时前
SpringCloud系列 - Seata 分布式事务(六)
分布式·spring·spring cloud
工藤学编程16 小时前
分库分表之实战-sharding-JDBC绑定表配置实战
数据库·分布式·后端·sql·mysql
gtestcandle16 小时前
rabbitmq 的多用户、多vhost使用
分布式·rabbitmq
老纪的技术唠嗑局16 小时前
单机分布式一体化数据库的架构设计与优化
数据库·分布式
SkyrimCitadelValinor17 小时前
Git【开源分布式版本控制工具】安装-配置-常用指令-Git远程仓库-IDEA使用Git
分布式·git·gitee·开源·项目管理