您的位置:首页 > 财经 > 产业 > 使用shedlock实现分布式互斥执行

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

2025/2/24 21:28:22 来源:https://blog.csdn.net/u011628753/article/details/140483919  浏览:    关键词:使用shedlock实现分布式互斥执行

前言

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

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

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

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

在这里插入图片描述

示例

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

  @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() {@Overridepublic 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,我们可以让一个方法不能在一个时间只能有一次实例在执行,排斥调用者,且其它调用者的调用失败,这是与分布式锁不一样的地方。

 @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() {@Overridepublic 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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com