分布式定时任务框架XXL-JOB

分布式定时任务框架XXL-JOB

杰子学编程 224 2022-07-01

分布式定时任务框架XXL-JOB

安装

1.1 管理端部署

1.1.1、初始化“调度数据库”

请下载项目源码并解压,获取 “调度数据库初始化SQL脚本” 并执行即可。

调度中心支持集群部署,集群情况下各节点务必连接同一个mysql实例;

如果mysql做主从,调度中心集群节点务必强制走主库;

1.1.2、编译源码

解压源码,按照maven格式将源码导入IDE, 使用maven进行编译即可,源码结构如下:

xxl-job-admin:调度中心
xxl-job-core:公共依赖
xxl-job-executor-samples:执行器Sample示例(选择合适的版本执行器,可直接使用,也可以参考其并将现有项目改造成执行器)
    :xxl-job-executor-sample-springboot:Springboot版本,通过Springboot管理执行器,推荐这种方式;
    :xxl-job-executor-sample-frameless:无框架版本;

1.1.3、配置部署“调度中心”

调度中心配置内容说明:

### 调度中心JDBC链接:链接地址请保持和 2.1章节 所创建的调度数据库的地址一致
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/xxl_job?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai
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
spring.mail.username=xxx@qq.com
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
### 调度中心通讯TOKEN [选填]:非空时启用;
xxl.job.accessToken=
### 调度中心国际化配置 [必填]: 默认为 "zh_CN"/中文简体, 可选范围为 "zh_CN"/中文简体, "zh_TC"/中文繁体 and "en"/英文;
xxl.job.i18n=zh_CN
## 调度线程池最大线程配置【必填】
xxl.job.triggerpool.fast.max=200
xxl.job.triggerpool.slow.max=100
### 调度中心日志表数据保存天数 [必填]:过期日志自动清理;限制大于等于7时生效,否则, 如-1,关闭自动清理功能;
xxl.job.logretentiondays=30

配置完成后,将打包好的xxl-job-admin上传到服务器中,进行部署。

部署成功后访问ip:8080,

WX20220701-140741@2x

至此“调度中心”项目已经部署成功。

1.2、配置部署“执行器项目”

maven依赖:

确认pom文件中引入了 “xxl-job-core” 的maven依赖

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

执行器配置

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

执行器组件配置

@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;
}

在SpringBoot,config中配置执行器。

1.3、使用示例

BEAN模式:任务以JobHandler方式维护在执行器端;需要结合 “JobHandler” 属性匹配执行器中任务;

在SpringBoot项目中创建需要处理定时任务的对象类。如下:

我们在需要执行的方法上增加@XxlJob("logRecordJob")注解。

@Slf4j
@Component
public class LogRecordJob {
    @Autowired
    ILogRecordService logRecordService;
    @Autowired
    private LoginRecordService loginRecordService;
    @Autowired
    IMessageService messageService;
    
    @XxlJob("logRecordJob")
    public void LogRecordJobHandler() {
        log.info("logRecordJob start...");
        // 查询即将逾期的记录:endTime+需求记录的最后一条记录
        LogRecordDTO logRecordDTO = new LogRecordDTO();
        logRecordDTO.setCreateTime(new Date());
        List<LogRecordDTO> logRecordList = logRecordService.selectLastReqLog(logRecordDTO);
        if (CollectionUtil.isEmpty(logRecordList)) {
            XxlJobHelper.log("logRecordList is null");
            return;
        }
        Date nowTime = new Date();
        for (LogRecordDTO recordDTO : logRecordList) {
            Long betweenHours = DateUtil.between(nowTime, recordDTO.getEndTime(), DateUnit.HOUR, false);
            XxlJobHelper.log("离逾期还有 {} 小时", betweenHours);
            log.info("离逾期还有 {} 小时", betweenHours);
            if (0 < betweenHours && betweenHours < 8) { // 大于0小于8小时,(可能逾期)发送消息提醒
                if (StrUtil.isNotBlank(recordDTO.getReceivers())) {
                    MessageDTO messageDTO = new MessageDTO();
                    List<String> receiverStr = Arrays.asList(recordDTO.getReceivers().split(","));
                    List<Long> receivers = receiverStr.stream().map(str -> Long.parseLong(str.trim())).collect(Collectors.toList());
                    messageDTO.setMsgReceiveUser(receivers);
                    String content = "您有一个即将逾期的需求:" + recordDTO.getBizCode() + ",请尽快处理!";
                    messageDTO.setMsgContent(content);
                    messageDTO.setMsgType(new Long(1));
                    messageDTO.setMsgStatus(new Long(1));
                    messageService.create(messageDTO);
                    XxlJobHelper.log("离逾期还有 {} 小时,发送消息", betweenHours, JSONUtil.toJsonStr(messageDTO));
                    log.info("离逾期还有 {} 小时,发送消息", betweenHours, JSONUtil.toJsonStr(messageDTO));
                }
            }
        }
        
    }
}

配置完成后,我们在xxl-job-admin中配置定时任务执行信息:

WX20220701-142208@2x

我在管理平台中配置定时任务执行周期和jobHandler。

注:执行器和管理端需网络互通。否则管理端无法调度执行器。


# SpringBoot # Starter # XXL-JOB # 分布式定时任务