分布式任务调度平台 → 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="//maven.apache.org/POM/4.0.0"
         xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="//maven.apache.org/POM/4.0.0 //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="//maven.apache.org/POM/4.0.0" xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="//maven.apache.org/POM/4.0.0 //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 是否搭建好了

    启动没报错,我们访问下://localhost:8080/xxl-job-admin,出现如下登录界面,则表示 xxl-job-admin 搭建完成

    

  my-project

    这个就是我们的项目工程,调度以外的代码该怎么写还是怎么写,下面我们只讲调度相关的

    实际项目中,任务调度往往会操作数据库,我们加入相关依赖,pom.xml 如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="//maven.apache.org/POM/4.0.0"
         xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="//maven.apache.org/POM/4.0.0 //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 "//address" or "//address01,//address02"
xxl.job.admin.addresses=//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-JOB

Tags: