用shedlock實現分佈式定時任務鎖

添加包java

<dependency>spring

     <groupId>net.javacrumbs.shedlock</groupId>
     <artifactId>shedlock-spring</artifactId>
     <version> 2.2 . 0 </version>
</dependency>
<dependency>
     <groupId>net.javacrumbs.shedlock</groupId>
     <artifactId>shedlock-provider-jdbc-template</artifactId>
     <version> 2.2 . 0 </version>
</dependency>
添加表

CREATE TABLE `shedlock` (
`name` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
`lock_until` timestamp(3) NULL DEFAULT NULL,
`locked_at` timestamp(3) NULL DEFAULT NULL,
`locked_by` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;sql

添加config數據庫

import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider;
import net.javacrumbs.shedlock.spring.ScheduledLockConfiguration;
import net.javacrumbs.shedlock.spring.ScheduledLockConfigurationBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.sql.DataSource;
import java.time.Duration;

@Configuration
@EnableScheduling
public class ShedlockConfig {

@Bean
public LockProvider lockProvider(DataSource dataSource) {
return new JdbcTemplateLockProvider(dataSource);
}

@Bean
public ScheduledLockConfiguration scheduledLockConfiguration(LockProvider lockProvider) {
return ScheduledLockConfigurationBuilder
.withLockProvider(lockProvider)
.withPoolSize(10)
.withDefaultLockAtMostFor(Duration.ofMinutes(10))
.build();
}
}
具體的定時任務
import net.javacrumbs.shedlock.core.SchedulerLock;
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "PT30S") //重點地方
public class MarkRefreshScheduler {

private final static Logger logger = LoggerFactory.getLogger(MarkRefreshScheduler.class);


//每週一早上5點執行一次,用戶的熱度值和hot標識歸零
@Scheduled(cron = "0 0/2 * * * ? ")
@SchedulerLock(name = "headNumCronName", lockAtMostFor = 5 * 1000, lockAtLeastFor = 5 * 1000)//重點地方
public void refreshHotSumAndIsOnTop() {
logger.info("begin refreshHotSumAndIsOnTop...");
//do something
logger.info("begin refreshHotSumAndIsOnTop...");

}
}
結果

經過修改數據庫表中的數據實現鎖ide

裏面有四個字段ui

主鍵name:每一個定時任務的一個名字spa

locked_at:鎖的開始時間3d

lock_until:鎖的結束時間code

再定時開始時,會更新這兩個時間,在時間以內的定時是不會被執行的blog

相關文章
相關標籤/搜索