使用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

相关推荐
shangjg323 分钟前
Kafka ACK机制详解:数据可靠性与性能的权衡之道
java·数据库·分布式·后端·kafka
[email protected]6 小时前
Asp.Net Core SignalR的分布式部署
分布式·后端·asp.net·.netcore
ErizJ18 小时前
Golang | 运用分布式搜索引擎实现视频搜索业务
分布式·搜索引擎·golang·全栈·grpc
wanhengidc18 小时前
影响服务器稳定性的因素都有什么?
运维·服务器·分布式
ghie90901 天前
matlab分布式电源接入对配电网的影响
分布式
快乐肚皮1 天前
Redisson学习专栏(二):核心功能深入学习(分布式锁,分布式集合,原子操作与计数器,事件与监听)
java·分布式·分布式锁·redisson·事件·分布式集合·原子
栗子~~1 天前
kafka 常用知识点
分布式·kafka
bigdata-rookie1 天前
kafka SASL/PLAIN 认证及 ACL 权限控制
大数据·运维·服务器·分布式·zookeeper·kafka
prince051 天前
Kafka多线程Consumer
分布式·kafka
炼金士1 天前
基于分布式状态机的集装箱智能道口软件架构方法
分布式·orleans·dapr·actor