加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

【SpringBoot实战】分布式定时任务锁Shedlock

(2022-05-12 20:31:21)

在我们业务开发过程中,经常会有需求做一些定时任务,但是由于定时任务的特殊性,以及一些方法的幂等性要求,在分布式多节点部署的情况下,某个定时任务只需要执行一次。

1. 背景介绍

ShedLock(https://github.com/lukas-krecan/ShedLock) 是一个轻量级的分布式定时任务锁组件,使用其可以满足我们上面的技术需求,ShedLock 官方简单自我介绍:

ShedLock makes sure that your scheduled tasks are executed at most once at the same time. If a task is being executed on one node, it acquires a lock which prevents execution of the same task from another node (or thread). Please note, that if one task is already being executed on one node, execution on other nodes does not wait, it is simply skipped.

Shedlock 从严格意义上来说不是一个分布式任务调度框架,而是一个分布式锁。所谓的分布式锁,解决的核心问题就是各个节点中无法通信的痛点。各个节点并不知道这个定时任务有没有被其他节点的定时器执行,所以理论上只需要有一个各个节点都能够访问到的资源,用这个资源去标记这个定时任务有没有执行就可以了。

[1]2. Shedlock 实现

Shedlock 实现分布式锁,可以依赖如下组件:

  • JdbcTemplate

  • Mongo

  • DynamoDB

  • DynamoDB 2

  • ZooKeeper (using Curator)

  • Redis (using Spring

  • RedisConnectionFactory)

  • Redis (using Jedis)

  • Hazelcast

  • Couchbase

  • ElasticSearch

  • CosmosDB

  • Cassandra

  • Multi-tenancy

本文主要以来 Redis 为公共存储,实现定时任务的分布式锁。首先,我们假设你的 Spring Boot 项目已经引入了 Redis,在项目的 pom 文件中加入依赖:


0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有