1. 程式人生 > >分散式任務排程平臺 → XXL-JOB 實戰

分散式任務排程平臺 → XXL-JOB 實戰

開心一刻

  老師:誰知道鞭炮用英語怎麼說?
  甲:老師!老師!我知道,鞭炮的英文是pilipala。
  老師:那閃電呢?
  乙:kucha kucha
  老師:那舞獅呢?
  丙:dong dong qiang
  老師:你們幾個先歇會吧!太費嗓子了!
  老師:下一個,誰知道墨家創始人墨子的英文怎麼翻譯?
  丁:black baby
  老師:那老子是不是叫old baby?好了最後一題!我們都知道有位大詩人叫陸游,請問他的英文名應該怎麼翻譯呢?
  辛:wifi
  同學們:啊哈哈哈哈!!!

前傾回顧

  分散式任務排程平臺 → XXL-JOB 初探 中,我們簡單介紹了 XXL-JOB,並簡單搭建了一個叢集環境

  可我們是在 XXL-JOB 官方的示例程式碼基礎上來搭建的,沒用應用到我們的專案中去

  那如何應用到我們的專案中去了,將 xxl-job-admin、xxl-job-core、xxl-job-executor 的原始碼都引入到我們的專案中 ?這樣可行,但沒必要

  我們細想下,xxl-job-admin 作為排程中心,有視覺化的 web 管理介面, 可將其作為一個模組以原始碼的方式引入到我們的專案中,我們可對其進行自定義的修改,但一般不需要;xxl-job-core 是 XXL-JOB 的核心,絕大多數情況下我們不用對其進行自定義(一方面它已滿足排程的常規需求,另一方面則是需要對 xxl-job-core 有一定的瞭解才敢去進行自定義的修改),那麼我們以 jar 依賴的方式引入即可;至於 xxl-job-executor,它是和我們專案結合最緊密的,也是需要我們自定義的,那麼我們參考官方的示例即可,不需要引入 xxl-job-executor 示例原始碼

  具體實現我們往下看

專案搭建

  專案結構如下

  

  此時只有架子,都是空實現(包括 pom.xml),我們一步一步的填充內容

  project-parent

    作為父工程,可以統一配置子工程中依賴的 jar 包的版本,具體內容如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lee</groupId>
    <artifactId>project-parent</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>xxl-job-admin</module>
        <module>my-project</module>
    </modules>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.test.skip>true</maven.test.skip>

        <netty-all.version>4.1.50.Final</netty-all.version>
        <gson.version>2.8.6</gson.version>

        <spring.version>5.2.7.RELEASE</spring.version>
        <spring-boot.version>2.3.0.RELEASE</spring-boot.version>

        <mybatis-spring-boot-starter.version>2.1.3</mybatis-spring-boot-starter.version>
        <mysql-connector-java.version>8.0.20</mysql-connector-java.version>

        <slf4j-api.version>1.7.30</slf4j-api.version>
        <junit.version>4.13</junit.version>
        <javax.annotation-api.version>1.3.2</javax.annotation-api.version>

        <groovy.version>3.0.4</groovy.version>

        <!-- xxl-job-core 作為依賴引入 -->
        <xxl-job-core-version>2.2.0</xxl-job-core-version>

        <lombok.version>1.16.22</lombok.version>

        <maven-source-plugin.version>3.2.1</maven-source-plugin.version>
        <maven-javadoc-plugin.version>3.2.0</maven-javadoc-plugin.version>
        <maven-gpg-plugin.version>1.6</maven-gpg-plugin.version>
        <maven-war-plugin.version>3.3.0</maven-war-plugin.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${mybatis-spring-boot-starter.version}</version>
            </dependency>

            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql-connector-java.version}</version>
            </dependency>

            <dependency>
                <groupId>com.xuxueli</groupId>
                <artifactId>xxl-job-core</artifactId>
                <version>${xxl-job-core-version}</version>
            </dependency>

            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${lombok.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>
View Code

  xxl-job-admin

    這個好處理,將官方示例原始碼中的 xxl-job-admin 的 src 資料夾直接拷貝過來覆蓋已有的 src,pom.xml 新增如下內容

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.lee</groupId>
        <artifactId>project-parent</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>xxl-job-admin</artifactId>
    <packaging>jar</packaging>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>

        <!-- starter-web:spring-webmvc + autoconfigure + logback + yaml + tomcat -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- starter-test:junit + spring-test + mockito -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- freemarker-starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

        <!-- mail-starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <!-- starter-actuator -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!-- mybatis-starter:mybatis + mybatis-spring + hikari(default) -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

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

    </dependencies>
</project>
View Code

    然後修改:application.properties 中的配置,例如埠號,資料庫連線地址、使用者名稱、密碼等等,改好之後我們啟動下,就知道 xxl-job-admin 是否搭建好了

    啟動沒報錯,我們訪問下:http://localhost:8080/xxl-job-admin,出現如下登入介面,則表示 xxl-job-admin 搭建完成

    

  my-project

    這個就是我們的專案工程,排程以外的程式碼該怎麼寫還是怎麼寫,下面我們只講排程相關的

    實際專案中,任務排程往往會操作資料庫,我們加入相關依賴,pom.xml 如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>project-parent</artifactId>
        <groupId>com.lee</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>my-project</artifactId>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>
View Code

    配置 application.properties

### web
server.port=8081
server.servlet.context-path=/my-project

### mybatis
mybatis.mapper-locations=classpath:/mybatis-mapper/*Mapper.xml
#mybatis.type-aliases-package=com.xxl.job.admin.core.model

### xxl-job, datasource
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/my_project?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

### datasource-pool
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.minimum-idle=10
spring.datasource.hikari.maximum-pool-size=30
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name=HikariCP
spring.datasource.hikari.max-lifetime=900000
spring.datasource.hikari.connection-timeout=10000
spring.datasource.hikari.connection-test-query=SELECT 1

# log config
logging.config=classpath:logback.xml


### xxl-job admin address list, such as "http://address" or "http://address01,http://address02"
xxl.job.admin.addresses=http://127.0.0.1:8080/xxl-job-admin

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

### xxl-job executor appname
xxl.job.executor.appname=my-project-executor
### xxl-job executor registry-address: default use address to registry , otherwise use ip:port if address is null
xxl.job.executor.address=
### xxl-job executor server-info
xxl.job.executor.ip=
xxl.job.executor.port=9999
### xxl-job executor log-path
xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler
### xxl-job executor log-retention-days
xxl.job.executor.logretentiondays=30
View Code

    新增 Job 執行器:XxlJobConfig.java

package com.lee.config;

import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class XxlJobConfig {
    private Logger logger = LoggerFactory.getLogger(com.lee.config.XxlJobConfig.class);

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

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

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

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

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

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

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

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


    @Bean
    public XxlJobSpringExecutor xxlJobExecutor() {
        logger.info(">>>>>>>>>>> xxl-job config init.");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
        xxlJobSpringExecutor.setAppname(appname);
        xxlJobSpringExecutor.setAddress(address);
        xxlJobSpringExecutor.setIp(ip);
        xxlJobSpringExecutor.setPort(port);
        xxlJobSpringExecutor.setAccessToken(accessToken);
        xxlJobSpringExecutor.setLogPath(logPath);
        xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);

        return xxlJobSpringExecutor;
    }

    /**
     * 針對多網絡卡、容器內部署等情況,可藉助 "spring-cloud-commons" 提供的 "InetUtils" 元件靈活定製註冊IP;
     *
     *      1、引入依賴:
     *          <dependency>
     *             <groupId>org.springframework.cloud</groupId>
     *             <artifactId>spring-cloud-commons</artifactId>
     *             <version>${version}</version>
     *         </dependency>
     *
     *      2、配置檔案,或者容器啟動變數
     *          spring.cloud.inetutils.preferred-networks: 'xxx.xxx.xxx.'
     *
     *      3、獲取IP
     *          String ip_ = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
     */


}
View Code

    新增 Job:UserJob.java

package com.lee.job;

import com.lee.model.User;
import com.lee.service.UserService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserJob {

    @Autowired
    private UserService userService;

    @XxlJob("userJobHandler")
    public ReturnT<String> userJobHandler(String param) throws Exception {
        System.out.println("hello, user...");

        // 查詢資料庫,業務處理後再寫回資料庫
        List<User> users = userService.listAll();
        System.out.println(users);

        return ReturnT.SUCCESS;
    }

}
View Code

    專案工程完整程式碼:my-xxl-job

  排程配置

    啟動 xxl-job-admin、my-project 後,在排程中心配置執行器

    

    配置任務

     

     具體配置過程、排程啟動、叢集搭建可檢視 分散式任務排程平臺 → XXL-JOB 初探

總結

  1、xxl-job-admin 基本按原始碼引入就好,基本不需要改動

  2、xxl-job-core 被 xxl-job-admin 和 xxl-job-executor 依賴,我們以 jar 包的方式依賴進來就好,無需引入原始碼

  3、xxl-job-executor 的改造其實也簡單,加入相應的配置,將我們常規的定時任務改成 xxl-job 的方式就好

  4、可能存在一些細節未講到,如果有不理解的地方,多看看 my-xxl-job 原始碼就好

參考

  XXL