手把手教你实现xxl-job分布式任务调度平台搭建

时间:2022-07-25
本文章向大家介绍手把手教你实现xxl-job分布式任务调度平台搭建,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

程序员的成长之路

互联网/程序员/技术/资料共享

关注

阅读本文大概需要 4.5 分钟。

编辑:业余草

推荐:https://www.xttblog.com/?p=5097

最近有网友咨询我 xxl-job 相关的问题,我认为官方文档已经写的非常详细了,这里我再给大家写一个入门级的 3 分钟实战 demo,希望能够帮助到更多的“新手用户”。

首先我们需要先下载 xxl-job 的源码,下载地址:github:https://github.com/xuxueli/xxl-job。我这里下载使用的是 2.1.2 版本,下载完成后解压,然后使用 IDEA 的Import Project 导入到 IDE 中,注意使用 Maven 方式导入。

将上图目录下的 sql 文件放入 mysql 中执行,执行完成之后会生成如下 8 张表。

然后我们需要修改 xxl-job-admin 工程下的 application.properties 配置文件。

主要修改的就是数据库连接属性,需要跟上面创建数据库表的数据库连接信息一致。

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

配置文件修改完毕之后,因为是一个 SpringBoot 项目,不需要再打成 war 包放入 tomcat 这种操作了,就可以直接启动 xxl-job-admin 的启动类。

成功启动之后,如果没有修改 application.properties 配置文件中的端口号和路径的话,直接打开 http://localhost:8080/xxl-job-admin 就能看到 xxl-job-admin 的监控平台了,默认用户名 admin,密码 123456。

到这里 xxl-job-admin 就搭建完成了,接下来我们写一个 demo,demo 中的代码均参考自官方网站 https://www.xuxueli.com/xxl-job/,有兴趣的同学可以自行查阅 项目结构如下:

首先导入 pom 依赖。

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

同样的需要修改配置文件 application.properties。

# web port
server.port=8081

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

### 调度中心部署跟地址 [选填]:如调度中心集群部署存在多个地址则用逗号分隔。执行器将会使用该地址进行"执行器心跳注册"和"任务结果回调";为空则关闭自动注册;
xxl.job.admin.addresses=http://127.0.0.1:8080/xxl-job-admin
### 执行器AppName [选填]:执行器心跳注册分组依据;为空则关闭自动注册
xxl.job.executor.appname=xxl-job-executor-sample
### 执行器IP [选填]:默认为空表示自动获取IP,多网卡时可手动设置指定IP,该IP不会绑定Host仅作为通讯实用;地址信息用于 "执行器注册" 和 "调度中心请求并触发任务";
xxl.job.executor.ip=
### 执行器端口号 [选填]:小于等于0则自动获取;默认端口为9999,单机部署多个执行器时,注意要配置不同执行器端口;
xxl.job.executor.port=9999
### 执行器通讯TOKEN [选填]:非空时启用;
xxl.job.accessToken=
### 执行器运行日志文件存储磁盘路径 [选填] :需要对该路径拥有读写权限;为空则使用默认路径;
xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler
### 执行器日志文件保存天数 [选填] : 过期日志自动清理, 限制值大于等于3时生效; 否则, 如-1, 关闭自动清理功能;
xxl.job.executor.logretentiondays=30

添加 logback.xml。

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false" scan="true" scanPeriod="1 seconds">
    <contextName>logback</contextName>
    <property name="log.path" value="/data/applogs/xxl-job/xxl-job-executor-sample-springboot.log"/>

    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.path}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log.path}.%d{yyyy-MM-dd}.zip</fileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n
            </pattern>
        </encoder>
    </appender>

    <root level="info">
        <appender-ref ref="console"/>
        <appender-ref ref="file"/>
    </root>
</configuration>

config 类。

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

    @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
    public XxlJobSpringExecutor xxlJobExecutor() {
        logger.info(">>>>>>>>>>> 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;
    }
}

最后是需要定时执行的任务逻辑,在 2.1.2 版本中,由原来基于 JobHandler 类任务开发方式,优化为支持基于方法的任务开发方式;因此,可以支持单个类中开发多个任务方法,进行类复用。

@Component
public class DemoXxxlJob {
    @XxlJob("demoJobHandler")
    public ReturnT<String> demoJobHandler(String param) throws Exception {
        XxlJobLogger.log("XXL-JOB, Hello World.");

        for (int i = 0; i < 5; i++) {
            XxlJobLogger.log("beat at:" + i);
            TimeUnit.SECONDS.sleep(2);
        }
        return ReturnT.SUCCESS;
    }
}

上面的代码使用的是简单任务示例(Bean 模式),还支持分片广播任务、命令行任务、跨平台 Http 任务、生命周期任务,任务初始化与销毁时,支持自定义相关逻辑;可根据自己的需要选择,在源码中的 xxl-job-executor-sample-springboot 都有相应的示例可供参考。

一切准备就绪之后,我们就可以在 xxl-job-admin 上建立执行器了。

新增任务。

选择你的操作。

执行完成后可查看调度日志。

日志详情。

到这里整个项目就搭建完成了,整个 demo 非常简单。很多人就是因为没用过 xxl-job,所以非常惧怕,等你认真翻一遍官网,动手再实践一遍,最终发现 xxl-job 是如此的简单!

<END>