elastic-job简单入门
简介
Elastic-Job是一个分布式调度解决方案,由两个相互独立的子项目Elastic-Job-Lite和Elastic-Job-Cloud组成。
Elastic-Job-Lite定位为轻量级无中心化解决方案,使用jar包的形式提供分布式任务的协调服务。
功能列表:
- 分布式调度协调
- 弹性扩容缩容
- 失效转移
- 错过执行作业重触发
- 作业分片一致性,保证同一分片在分布式环境中仅一个执行实例
- 自诊断并修复分布式不稳定造成的问题
- 支持并行调度
- 支持作业生命周期操作
- 丰富的作业类型
- Spring整合以及命名空间提供
- 运维平台
入门开发
pom文件
<dependency>
<groupId>com.dangdang</groupId>
<artifactId>elastic-job-lite-core</artifactId>
<version>2.1.5</version>
</dependency>
<!-- 使用springframework自定义命名空间时引入 -->
<dependency>
<groupId>com.dangdang</groupId>
<artifactId>elastic-job-lite-spring</artifactId>
<version>2.1.5</version>
</dependency>
<?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:job="http://www.dangdang.com/schema/ddframe/job"
xmlns:reg="http://www.dangdang.com/schema/ddframe/reg"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.dangdang.com/schema/ddframe/job
http://www.dangdang.com/schema/ddframe/job/job.xsd
http://www.dangdang.com/schema/ddframe/reg
http://www.dangdang.com/schema/ddframe/reg/reg.xsd">
<!--Zookeeper注册中心 -->
<reg:zookeeper id="regCenter" server-lists="127.0.0.1:2181"
namespace="elastic-job" base-sleep-time-milliseconds="1000" max-sleep-time-milliseconds="3000" max-retries="3" />
<!-- 配置作业-->
<job:simple id="myElasticJob" class="com.job.MyElasticJob" registry-center-ref="regCenter"
cron="0/30 * * * * ?" sharding-total-count="1" overwrite="true"
event-trace-rdb-data-source="dataSource"/>
</beans>
当在<job:simple>中配置了数据源(如上)时,会自动创建两张数据库表分别是JOB_EXECUTION_LOG和JOB_STATUS_TRACE_LOG
JOB_EXECUTION_LOG记录每次作业的执行历史。分为两个步骤:
-
作业开始执行时向数据库插入数据,除failure_cause和complete_time外的其他字段均不为空。
-
作业完成执行时向数据库更新数据,更新is_success, complete_time和failure_cause(如果作业执行失败)。
JOB_STATUS_TRACE_LOG记录作业状态变更痕迹表。可通过每次作业运行的task_id查询作业状态变化的生命周期和运行轨迹。
实现SimleJob接口
public class MyElasticJob implements SimpleJob {
public void execute(ShardingContext shardingContext) {
//1.当分片数为1时,在同一个zookepper和jobname情况下,多台机器部署了Elastic job时,
// 只有拿到shardingContext.getShardingItem()为0的机器得以执行,其他的机器不执行
//总片数
int shardingTotalCount = shardingContext.getShardingTotalCount();
//当前分片项
int shardingItem = shardingContext.getShardingItem();
switch (shardingItem){
case 0:
run();
break;
case 1:
break;
}
}
private void run(){
//dosometing
}
}

浙公网安备 33010602011771号