1.pom文件
redis必须项: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> shedlock必须项: <dependency> <groupId>net.javacrumbs.shedlock</groupId> <artifactId>shedlock-spring</artifactId> <version>4.19.1</version> </dependency> shedlock可选项(此处采用redis实现,也可采用其他数据库,详见官网https://github.com/lukas-krecan/ShedLock): <dependency> <groupId>net.javacrumbs.shedlock</groupId> <artifactId>shedlock-provider-redis-spring</artifactId> <version>2.5.0</version> </dependency>
2.shedLock配置
@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "10m")
public class ShedLockConfig {
@Resource
RedisTemplate<String, Object> redisTemplate;
@Bean
public LockProvider lockProvider() {
return new RedisLockProvider(redisTemplate.getConnectionFactory());
}
}
3.开启任务
@Slf4j @Component public class TaskRun { @Scheduled(cron = "0 0 */1 * * ?") @SchedulerLock(name = "fylr") public void fylr() { System.out.println("run ..."); } }