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記錄每次作業的執行歷史。分為兩個步驟:

  1. 作業開始執行時向數據庫插入數據,除failure_cause和complete_time外的其他字段均不為空。

  2. 作業完成執行時向數據庫更新數據,更新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
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM