利用ShedLock组件 + spring scheduling实现简单的分布式调度

https://github.com/lukas-krecan/ShedLock

  • pom.xml
1
2
3
4
5
6
7
8
9
10

<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-spring</artifactId>
</dependency>

<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-provider-jedis</artifactId>
</dependency>
  • config
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* @author : 披荆斩棘
* @date : 2017/6/22
*/
@Getter
@Setter
@Configuration
@ConfigurationProperties( prefix = "redis" )
public class BeanConfig {

private String host;
private Integer port;
private Integer timeout;


@Bean
public JedisPoolConfig jedisPoolConfig () {
JedisPoolConfig config = new JedisPoolConfig();
return config;
}

@Bean
public JedisPool jedisPool () {
return new JedisPool( jedisPoolConfig(), host, port, timeout );
}

/**
* 配置锁
*
* @param jedisPool
* @return
*/
@Bean
public LockProvider lockProvider ( JedisPool jedisPool ) {
return new JedisLockProvider( jedisPool, "data-platform-scheduling" );
}


/**
* 计划任务分布式锁配置,保证在多个实例下,任务只在一台机器上运行.
*
* @param lockProvider
* @return
*/
@Bean
public ScheduledLockConfiguration taskScheduler ( LockProvider lockProvider ) {
return ScheduledLockConfigurationBuilder
.withLockProvider( lockProvider )
.withPoolSize( 30 )
.withDefaultLockAtMostFor( Duration.ofHours( 24 ) )
.build();
}
}
  • task
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Component
public class DemoTask implements EnvironmentAware {

private StandardServletEnvironment environment;

@Scheduled( cron = "*/3 * * * * *" )
@SchedulerLock( name = "DemoTask" )
public void test () {
System.err.println( environment.getPropertySources()
.get( "server.ports" )
.getSource() + " : DemoTask test run " );
}

@Override
public void setEnvironment ( Environment environment ) {
this.environment = ( StandardServletEnvironment ) environment;
}
}

完成,这样就实现了分布式调度

实现原理是基于分布式锁实现的,具体可以去看源码

具体代码 https://github.com/yujunhao8831/spring-boot-start-current