背景:
ShedLock 是一个用于分布式系统中防止定时任务重复执行的库。它确保在集群环境中,只有一个实例会执行特定的定时任务,即使有多个实例在运行。这对于需要保证任务幂等性和一致性的情况非常有用
应用场景:
-
分布式系统:在微服务架构中,多个实例可能会部署在不同的服务器上。使用 ShedLock 可以确保某个定时任务在同一时间只在一个实例上执行。
-
高可用性:即使某些实例宕机或重启,ShedLock 也能确保任务仍然按计划执行。
-
负载均衡:在负载均衡环境下,避免多个实例同时执行相同的定时任务。
实现步骤
使用 Redis 作为存储后端来实现 ShedLock。
1、添加依赖
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter Data Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- ShedLock Spring Support -->
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-spring-support</artifactId>
<version>5.0.0</version>
</dependency>
<!-- ShedLock Provider for Redis -->
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-provider-redis-spring</artifactId>
<version>5.0.0</version>
</dependency>
<!-- Spring Boot Starter Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2、配置redis
在 application.properties
或 application.yml
文件中配置 Redis 连接信息。
application.properties:
# Server Configuration
server.port=8080
# Fixed Rate in milliseconds
fixed.rate.in.milliseconds=5000
# Redis Configuration
spring.redis.host=localhost
spring.redis.port=6379
</