一、分布式锁配置
(1)redis锁
pom.xml
<dependency><groupId>net.javacrumbs.shedlock</groupId><artifactId>shedlock-spring</artifactId><version>2.5.0</version>
</dependency><dependency><groupId>net.javacrumbs.shedlock</groupId><artifactId>shedlock-provider-redis-spring</artifactId><version>2.5.0</version>
</dependency>
自动配置
@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "PT30S")
public class DataSourceConfig {@Beanpublic LockProvider scheduledLockConfiguration(@Autowired RedisConnectionFactory connectionFactory) {return new RedisLockProvider(connectionFactory);}}
(2)数据库锁
pom.xml
<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>
自动配置
@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "PT30S")
public class DataSourceConfig {@Beanpublic scheduledLockConfiguration(@Autowired DataSource dataSource) {return new JdbcTemplateLockProvider(dataSource);}}
二、定时任务配置
@Component
public class CronTask {@Scheduled(cron="0 0/1 * * * ?")@SchedulerLock(name = "test-lock:testMethod", lockAtMostFor = 3 * 60 * 1000, lockAtLeastFor = 30 * 1000)public void testMethod(){//do something}}