一、项目中一般都会有定时任务,如何保证定时任务在集群只执行一次,可以通过elastic-job 实现定时任务分布式部署。
(1)增加elastic-job 对于配置文件的依赖
<dependency>
<groupId>com.dangdang</groupId>
<artifactId>elastic-job-lite-core</artifactId>
<version>2.1.5</version>
</dependency>
<dependency>
<groupId>com.dangdang</groupId>
<artifactId>elastic-job-lite-spring</artifactId>
<version>2.1.5</version>
</dependency>
2、增加xml配置文件dangdang-es-job.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:reg="http://www.dangdang.com/schema/ddframe/reg"
xmlns:job="http://www.dangdang.com/schema/ddframe/job"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.dangdang.com/schema/ddframe/reg
http://www.dangdang.com/schema/ddframe/reg/reg.xsd
http://www.dangdang.com/schema/ddframe/job
http://www.dangdang.com/schema/ddframe/job/job.xsd">
<!--注册中心 -->
<reg:zookeeper id="regCenter" server-lists="192.168.25.133:2181" namespace="dd-job"
base-sleep-time-milliseconds="1000" max-sleep-time-milliseconds="3000" max-retries="3" />
<!--configure job -->
<job:simple id="testElasticJob" class="com.yin.databaseproject.job.TimeTask" registry-center-ref="regCenter"
cron="0/10 * * * * ?" sharding-total-count="1" failover="true" />
</beans>
3、在启动类中增加对xml文件的加载(此处继承 SpringBootServletInitializer 是为用tomcat启动测试集群部署是否重复执行)
@SpringBootApplication
@ImportResource(locations= {"classpath:conf/dangdang-es-job.xml"})
public class DatabaseProjectApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(DatabaseProjectApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(DatabaseProjectApplication.class, args);
}
}
4、写任务执行类
public class TimeTask implements SimpleJob {
@Override
public void execute(ShardingContext shardingContext) {
String jobName = shardingContext.getJobName();
int shardingItem = shardingContext.getShardingItem();
System.out.println(shardingItem+":::"+jobName);
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss:SSS");
String date =formatter.format(new Date());
System.out.println("123333"+date);
}
}