分布式定时任务锁SchedulerLock
ShedLock的实现原理是采用公共存储实现的锁机制,确保任务在同一时刻最多执行一次。如果一个任务正在一个节点上执行,则它将获得一个锁,该锁将阻止从另一个节点(或线程)执行同一任务。
如果一个任务已经在一个节点上执行,则在其他节点上的执行不会等待,只需跳过它即可 。
配置和使用:
依赖配置:
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-spring</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-provider-jdbc-template</artifactId>
<version>2.3.0</version>
</dependency>
配置类config
@Component
public class ShedLockConfig {
@Bean
public LockProvider lockProvider(DataSource dataSource) {
return new JdbcTemplateLockProvider(dataSource,tableName);
}
@Bean
public ScheduledLockConfiguration scheduledLockConfiguration(LockProvider lockProvider) {
return ScheduledLockConfigurationBuilder.withLockProvider(lockProvider)
.withPoolSize(10)
.withDefaultLockAtMostFor(Duration.ofMinutes(10))
.build();
}
}
启动类的配置:
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "PT30S")
执行任务的方法:
@Component
private static final int SYSUSERMOST = 58*60*1000;
private static final int SYSUSERLEAST = 58*60*1000;
@Scheduled(cron = "0 0 23 * * ? ")
@SchedulerLock(name = "JobName", lockAtMostFor = SYSUSERMOST, lockAtLeastFor = SYSUSERLEAST)
@Transactional(rollbackFor = Exception.class)
public void syncDataUser() throws IOException {
代码省略........
}