admin管理员组

文章数量:1794759

定时任务 @Schedule注解 分布式加锁

定时任务 @Schedule注解 分布式加锁

@Schedule注解可以在sprintboot项目中定时启动某个方法,但是如果是分布式部署方案,如k8s集群等,每个节点都会运行此方法,就会造成一系列的问题,此时就要用到@SchedulerLock 分布式加锁注解

maven:

<dependency> <groupId>net.javacrumbs.shedlock</groupId> <artifactId>shedlock-spring</artifactId> <version>0.16.1</version> </dependency> <dependency> <groupId>net.javacrumbs.shedlock</groupId> <artifactId>shedlock-provider-jdbc-template</artifactId> <version>0.16.1</version> </dependency>

config配置类:

@Configuration @EnableScheduling public class ShedlockConfig { @Value("${spring.datasource.primary.url}") private String url; @Value("${spring.datasource.primary.username}") private String username; @Value("${spring.datasource.primary.password}") private String password; @Value("${spring.datasource.primary.driver-class-name}") private String driverClassName; @Value("${spring.datasource.primary.initialSize}") private int initialSize; @Value("${spring.datasource.primary.minIdle}") private int minIdle; @Value("${spring.datasource.primary.maxActive}") private int maxActive; @Value("${spring.datasource.primary.maxWait}") private int maxWait; //从配置文件获取,也可以自己手动填进去 @Bean public LockProvider lockProvider() { DruidDataSource druid = new DruidDataSource(); druid.setUrl(url); druid.setUsername(username); druid.setPassword(password); druid.setDriverClassName(driverClassName); druid.setMinIdle(minIdle); druid.setMaxWait(maxWait); druid.setInitialSize(initialSize); druid.setMaxActive(maxActive); return new JdbcTemplateLockProvider( JdbcTemplateLockProvider.Configuration.builder() .withJdbcTemplate(new JdbcTemplate(druid)) // .usingDbTime() // Works on Postgres, MySQL, MariaDb, MS SQL, Oracle, DB2, HSQL and H2 .build() ); } }

数据库建表,sql语句:

CREATE TABLE shedlock( name VARCHAR(64), lock_until TIMESTAMP(3) NULL, locked_at TIMESTAMP(3) NULL, locked_by VARCHAR(255), PRIMARY KEY (name) )

使用:

//2分钟一次 @Scheduled(fixedRate = 120000) //主键downloadCenterFtpSync ,加锁时间为2分钟 @SchedulerLock(name = "downloadCenterFtpSync", lockAtMostFor = 120000, lockAtLeastFor = 120000) public void downloadCenterFtpSync() throws ParseException { log.info("Enter download center files sync . date:{}", DateUtil.now()); long startTime = System.currentTimeMillis(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SftpHutoolExt sftpHutoolExt = new SftpHutoolExt(querySftpInfo.getFtpConfig("requestId"));

数据库: 表字段必须一致,所有的操作都由SchedulerLock 完成

本文标签: 注解分布式加锁schedule