Spring Cloud | xxl-job的使用

一、簡述

XXL-JOB是一個輕量級分佈式任務調度平臺,其核心設計目標是開發迅速、學習簡單、輕量級、易擴展。現已開放源代碼並接入多家公司線上產品線,開箱即用。
通過xxl-job的方式調度任務,實現定時任務是非常方便的。

官方文檔:http://www.xuxueli.com/xxl-job/

本章案例源碼:
源碼:https://github.com/liujun19921020/SpringCloudDemo/blob/master/ProjectDemo/企業SpringCloud架構-xxljob-redis-elasticsearch
或 :鏈接:https://pan.baidu.com/s/1ooqaIRSeX6naOZ51aBWNHA  提取碼:cwsw

這裏是整了一個架構集合案例,其中的ES將在下章講解,該文主要源碼爲sc-xxl-job-demo項目。

二、目標

這裏我們講述的目標功能是:每日凌晨備份前一天的數據庫表,共保留2天的備份表。
例:29日凌晨備份order_amazon表,取名爲order_amazon_29,並刪除2天前的備分表order_amazon_27

三、搭建調度中心xxl-job-demo

調度中心的搭建請參考官方文檔,有詳細的步驟說明。大致如下:
1、下載源碼並解壓(xxl-job-admin項目即爲調度中心)
2、初始化sql腳本 (/xxl-job/doc/db/tables_xxl_job.sql)
3、更改配置中心配置 (/xxl-job/xxl-job-admin/src/main/resources/xxl-job-admin.properties)
    配置內容說明:

    ### 調度中心JDBC鏈接:鏈接地址請保持和 2.1章節 所創建的調度數據庫的地址一致
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/xxl_job?Unicode=true&characterEncoding=UTF-8
    spring.datasource.username=root
    spring.datasource.password=root_pwd
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver

    ### 報警郵箱
    spring.mail.host=smtp.qq.com
    spring.mail.port=25
    [email protected]
    spring.mail.password=xxx
    spring.mail.properties.mail.smtp.auth=true
    spring.mail.properties.mail.smtp.starttls.enable=true
    spring.mail.properties.mail.smtp.starttls.required=true
    spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory

    ### xxl-job, access token
    xxl.job.accessToken=

    ### xxl-job, i18n (default empty as chinese, "en" as english)
    xxl.job.i18n=

4、打包部署xxl-job-admin項目即可

  •     調度中心訪問地址 例:http://localhost:8080/xxl-job-admin (該地址執行器將會使用到,作爲回調地址)
  •     默認登錄賬號 "admin/123456", 登錄後運行界面如下圖所示:


    
    
四、搭建執行器項目

執行器項目即爲我們需要實現的功能項目,配置步驟官方文檔也較詳細。下面我們來實現代碼:
創建一個spring boot項目,數據源配置、結構等請參考前幾篇文章。

先引入xxl-job的配置
1、pom.xml中引入"xxl-job-core" 的maven依賴
 

<dependency>
    <groupId>com.xuxueli</groupId>
    <artifactId>xxl-job-core</artifactId>
    <version>2.0.1</version>
</dependency>

2、在application.properties配置文件中添加執行器配置,內容如下:

### 調度中心部署跟地址 [選填]:如調度中心集羣部署存在多個地址則用逗號分隔。執行器將會使用該地址進行"執行器心跳註冊"和"任務結果回調";爲空則關閉自動註冊;
xxl.job.admin.addresses=http://xxljob.dev.java.yibainetworklocal.com/xxl-job-admin

### 執行器AppName [選填]:執行器心跳註冊分組依據;爲空則關閉自動註冊
xxl.job.executor.appname=sc-xxl-job-demo-handler

### 執行器IP [選填]:默認爲空表示自動獲取IP,多網卡時可手動設置指定IP,該IP不會綁定Host僅作爲通訊實用;地址信息用於 "執行器註冊" 和 "調度中心請求並觸發任務";
xxl.job.executor.ip=

### 執行器端口號 [選填]:小於等於0則自動獲取;默認端口爲9999,單機部署多個執行器時,注意要配置不同執行器端口;
xxl.job.executor.port=8800

### 執行器通訊TOKEN [選填]:非空時啓用;
xxl.job.accessToken=

### 執行器運行日誌文件存儲磁盤路徑 [選填] :需要對該路徑擁有讀寫權限;爲空則使用默認路徑;
xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler

### 執行器日誌保存天數 [選填] :值大於3時生效,啓用執行器Log文件定期清理功能,否則不生效;
xxl.job.executor.logretentiondays=-1

3、添加對應的引用類XxlJobConfig.java(@ComponentScan後配置的包路徑即爲任務的入口,屆時掃描)

@Configuration
@ComponentScan(basePackages = "com.lj.scxxljobdemo.jobhandler")
public class XxlJobConfig {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${xxl.job.admin.addresses}")
    private String adminAddresses;

    @Value("${xxl.job.executor.appname}")
    private String appName;

    @Value("${xxl.job.executor.ip}")
    private String ip;

    @Value("${xxl.job.executor.port}")
    private int port;

    @Value("${xxl.job.accessToken}")
    private String accessToken;

    @Value("${xxl.job.executor.logpath}")
    private String logPath;

    @Value("${xxl.job.executor.logretentiondays}")
    private int logRetentionDays;

    @Bean(initMethod = "start", destroyMethod = "destroy")
    public XxlJobSpringExecutor xxlJobExecutor() {
        logger.debug(">>>>>>>>>>> xxl-job config init.");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
        xxlJobSpringExecutor.setAppName(appName);
        xxlJobSpringExecutor.setIp(ip);
        xxlJobSpringExecutor.setPort(port);
        xxlJobSpringExecutor.setAccessToken(accessToken);
        xxlJobSpringExecutor.setLogPath(logPath);
        xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);

        return xxlJobSpringExecutor;
    }
}

 

xxl-job的引入配置在這裏即已結束,接下來實現業務代碼,項目入口放置在XxlJobConfig.java中配置的掃描路徑下,繼承自IJobHandler的Java類代碼:

package com.lj.scxxljobdemo.jobhandler;

/**
 * cs1db庫 表數據備份
 */
@JobHandler(value = "cs1DbJobHandler")
@Component
public class Cs1DbJobHandler extends IJobHandler {

    @Autowired
    ICs1DbService cs1DbService;

    @Override
    public ReturnT<String> execute(String s){
        try {
            String[] tableNameList = new String[]{"order_amazon","order_amazon_detail"};//要同步的表名

            CountDownLatch latch = new CountDownLatch(tableNameList.length);//設置與表相同的線程計數器,同時備份表
            for(String tableName : tableNameList){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            cs1DbService.tableOperation(tableName);
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            latch.countDown();
                        }
                    }
                }).start();
            }
            latch.await();
            return SUCCESS;
        } catch (InterruptedException e) {
            e.printStackTrace();
            return FAIL;
        }
    }
}


通過業務代碼,依次調用mybatis的xml進行建表、推數據、刪表操作

<mapper namespace="com.lj.scxxljobdemo.mapper.cs1db.Cs1DbMapper">

    <insert id="createTableName">
         DROP TABLE IF EXISTS ${tableName}_${dateName};
         CREATE TABLE ${tableName}_${dateName} LIKE ${tableName}
    </insert>

    <insert id="addTableData">
        INSERT INTO ${tableName}_${dateName} SELECT * FROM ${tableName}
    </insert>

    <delete id="deleteTableName" >
        DROP TABLE IF EXISTS ${tableName}_${dateName}
    </delete>
</mapper>


五、通過調度中心啓動定時任務

1、訪問調度中心(這裏使用搭建的http://xxljob.dev.java.yibainetworklocal.com/xxl-job-admin 爲例)

2、配置"執行器管理",注意對應application.properties中的配置信息

3、配置執行器的對應"任務管理"新增任務

 

執行任務後:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章