一、项目集成xxl-job的整体逻辑说明
项目的工程代码通过集成xxl-job,作为一个执行器注册到调度中心(xxl-job-admin)
官网地址:https://www.xuxueli.com/xxl-job/
二、集成步骤:
1、application.yml 增加配置
server:
port: 8083
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/safety_edu?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai
username: root
password: root
mybatis-plus:
mapper-locations: classpath:mapper/*Mapper.xml
#xxl-job 配置
xxl:
job:
accessToken:
#调度中心地址
admin:
addresses: http://127.0.0.1:8080/xxl-job-admin
#执行器配置
executor:
address:
appname: xxl-job-executor-leo
ip:
logpath: /data/applogs/xxl-job/jobhandler
logretentiondays: 30
port: 9997
2、pom 增加依赖,当前最新版为2.3.0
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-job-core</artifactId>
<version>2.3.0</version>
</dependency>
3、执行器配置类初始化
package com.leo.xxljob.config;
import com.leo.xxljob.jobhandler.ClassHandler;
import com.leo.xxljob.util.SpringContextUtil;
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;
/**
* xxl-job config
*
* @author xuxueli 2017-04-28
*/
@Configuration
public class XxlJobConfig {
private Logger logger = LoggerFactory.getLogger(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);
// 此处使用spring 上下文获取spring 容器中的实例,
// 因为,bean 模式,无法自动注入,需要通过执行器的静态方法XxlJobSpringExecutor.registJobHandler()注入任务处理器
ClassHandler classHandler = (ClassHandler)SpringContextUtil.getBean(ClassHandler.class);
XxlJobSpringExecutor.registJobHandler("leoClassHandler", classHandler);
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();
*/
}
4、调度job 开发,(bean 类模式)
package com.leo.xxljob.jobhandler;
import com.google.gson.Gson;
import com.leo.xxljob.util.SpringContextUtil;
import com.leo.xxljob.domain.ChapterContentBo;
import com.leo.xxljob.mapper.ChapterContentMapper;
import com.leo.xxljob.util.EnvironmentUtils;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.IJobHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 该集成方式官网不推荐使用,所以在v2.2.0以后已经去除了注解 JobHandler
* bean(java类模式)实现任务调度
* 步骤一: 创建java类继承IJobHandler 抽象类
* 步骤二:执行器配置代码中,手动注册该类 (详情XxlJobConfig.java)
* @author liuao
* @date 2021/8/16 16:17
*/
@Component("leoClassHandler")
@Slf4j
public class ClassHandler extends IJobHandler {
@Autowired
private ChapterContentMapper chapterContentMapper;
/**
* @author liuao
* @date 2021/8/16 16:17
*/
@Override
public void execute() throws Exception {
String param = XxlJobHelper.getJobParam();
ChapterContentBo contentBo = chapterContentMapper.selectById(1);
Gson gson = new Gson();
String res = gson.toJson(contentBo);
XxlJobHelper.log("查询结果:{}",res);
log.info("执行参数:{}",param);
// 使用XxlJobHelper.log 打印日志,可以在“任务调度中心”中的调度日志中看到
XxlJobHelper.log("ip {},端口:{}",
EnvironmentUtils.get("xxl.job.executor.ip"), EnvironmentUtils.get("xxl.job.executor.port"));
}
}
5、(bean 方法模式)
package com.leo.xxljob.jobhandler;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.leo.xxljob.domain.ChapterContentBo;
import com.leo.xxljob.mapper.ChapterContentMapper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
/**
* XxlJob开发示例(Bean方法模式)
*
* 开发步骤:
* 1、任务开发:在Spring Bean实例中,开发Job方法;
* 2、注解配置:为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")",注解value值对应的是调度中心新建任务的JobHandler属性的值。
* 3、执行日志:需要通过 "XxlJobHelper.log" 打印执行日志;
* 4、任务结果:默认任务结果为 "成功" 状态,不需要主动设置;如有诉求,比如设置任务结果为失败,可以通过 "XxlJobHelper.handleFail/handleSuccess" 自主设置任务结果;
*
* @author xuxueli 2019-12-11 21:52:51
*/
@Component
@Slf4j
public class MethodHandler {
private static Logger logger = LoggerFactory.getLogger(MethodHandler.class);
@Autowired
private ChapterContentMapper chapterContentMapper;
@Value("${xxl.job.executor.ip}")
private String ip;
@Value("${xxl.job.executor.port}")
private int port;
/**
* 1、简单任务示例(Bean方法模式)
*/
@XxlJob("leoJobHandler")
public void demoJobHandler() throws Exception {
// 获取调度中心传递的执行参数
String param = XxlJobHelper.getJobParam();
// 使用XxlJobHelper.log 打印日志,可以在“任务调度中心”中的调度日志中看到
XxlJobHelper.log("XXL-JOB, leo demo");
QueryWrapper<ChapterContentBo> queryWrapper = new QueryWrapper<>();
List<ChapterContentBo> lst = chapterContentMapper.selectList(queryWrapper);
log.info("查询结果:{}", lst.size());
log.info("执行参数:{}", param);
XxlJobHelper.log("ip {},端口:{}", ip, port);
}
/**
* 2、分片广播任务
*/
@XxlJob("shardingJobHandler")
public void shardingJobHandler() throws Exception {
// 分片参数
int shardIndex = XxlJobHelper.getShardIndex();
int shardTotal = XxlJobHelper.getShardTotal();
XxlJobHelper.log("分片参数:当前分片序号 = {}, 总分片数 = {}", shardIndex, shardTotal);
// 业务逻辑
for (int i = 0; i < shardTotal; i++) {
if (i == shardIndex) {
XxlJobHelper.log("第 {} 片, 命中分片开始处理", i);
} else {
XxlJobHelper.log("第 {} 片, 忽略", i);
}
}
}
}