SpringBoot_Xxl-Job
新建 xxl-job-demo 项目,熟悉原生 xxl-job 项目工作原理
第一步
- 添加 pom.xml 文件
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-job-core</artifactId>
<version>2.3.0</version>
</dependency>
第二步
- 添加配置文件
# web port
server.port=8082
# log config
logging.config=classpath:logback.xml
spring.application.name=xxl-job-demo
### 调度中心部署跟地址 [选填]:如调度中心集群部署存在多个地址则用逗号分隔。执行器将会使用该地址进行"执行器心跳注册"和"任务结果回调";为空则关闭自动注册;
xxl.job.admin.addresses=http://localhost:8080/xxl-job-admin
### 执行器通讯TOKEN [选填]:非空时启用;
xxl.job.accessToken=
### 执行器AppName [选填]:执行器心跳注册分组依据;为空则关闭自动注册
xxl.job.executor.appname=xxl-job-demo
### 执行器注册 [选填]:优先使用该配置作为注册地址,为空时使用内嵌服务 ”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=10
第三步
- 定义配置类
@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);
return xxlJobSpringExecutor;
}
}
第四步
- 定义运行的 Handler
@Component
public class XxlJobDemoHandler {
/**
* Bean模式,一个方法为一个任务
* 1、在Spring Bean实例中,开发Job方法,方式格式要求为 "public ReturnT<String> execute(String param)"
* 2、为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")",注解value值对应的是调度中心新建任务的JobHandler属性的值。
* 3、执行日志:需要通过 "XxlJobLogger.log" 打印执行日志;
*/
@XxlJob("demoJob")
public ReturnT<String> demoJob(String param) throws Exception {
XxlJobHelper.log("java, Hello World~~~");
XxlJobHelper.log("param:" + param);
return ReturnT.SUCCESS;
}
}
改造原生 xxl-job 适配对应的项目业务
这里项目之间的调用是通过 Feign,因此需要对原本的项目进行简单的改造,xxl-job 需要作为服务的提供者对外提供服务。
第一步
- 添加 pom.xml 对应的 Feign 依赖
<properties>
<spring-cloud.version>2020.0.4</spring-cloud.version>
<spring-cloud-alibaba.version>2021.1</spring-cloud-alibaba.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<!-- 使用spring loadbalancer,弃用ribbon -->
<exclusions>
<exclusion>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</exclusion>
<exclusion>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
<version>2.0.3</version>
</dependency>
</dependencies>
第二步
- 添加配置文件
spring.application.name=xxl-job-service-demo1
spring.cloud.nacos.discovery.server-addr=172.16.0.127:8848
在 xxl-job 中,关于任务的新增,修改,触发都在 JobInfoController 这个类之中,但这个类是提供给后台使用的,直接使用需要登录验证,如果这个时候修改 xxl-job 代码,会破坏原本框架的结构,后续业务的扩展和错误的排查会变的很麻烦
这里提供一个思路:重写对应的方法,然后添加上 @PermissionLimit(limit = false) 注解即可。
举例
xxl-job 新增任务的方法如下:
@RequestMapping("/add") @ResponseBody public ReturnT<String> add(XxlJobInfo jobInfo) { return xxlJobService.add(jobInfo); }
重写后的方法如下:
@RequestMapping("/addJob") @ResponseBody @PermissionLimit(limit = false) public ReturnT<String> addJob(@RequestBody XxlJobInfo jobInfo) { return xxlJobService.add(jobInfo); }
后续的使用,直接调用对应的 addJob,这样既不破坏原本的框架结构,又满足了对应的业务。
第三步
- 重写 xxl-job 里的方法
// 新增任务
@RequestMapping("/addJob")
@ResponseBody
@PermissionLimit(limit = false)
public ReturnT<String> addJob(@RequestBody XxlJobInfo jobInfo) {
return xxlJobService.add(jobInfo);
}
// 更新任务
@RequestMapping("/updateJob")
@ResponseBody
@PermissionLimit(limit = false)
public ReturnT<String> updateJob(@RequestBody XxlJobInfo jobInfo) {
return xxlJobService.update(jobInfo);
}
// 删除任务
@RequestMapping("/removeJob")
@ResponseBody
@PermissionLimit(limit = false)
public ReturnT<String> removeJob(Integer id) {
return xxlJobService.remove(id);
}
// 停止任务
@RequestMapping("/stopJob")
@ResponseBody
@PermissionLimit(limit = false)
public ReturnT<String> pauseJob(Integer id) {
return xxlJobService.stop(id);
}
// 开始任务
@RequestMapping("/startJob")
@ResponseBody
@PermissionLimit(limit = false)
public ReturnT<String> startJob(Integer id) {
return xxlJobService.start(id);
}
// 添加并开始任务
@RequestMapping("/addAndStart")
@ResponseBody
@PermissionLimit(limit = false)
public ReturnT<String> addAndStart(@RequestBody XxlJobInfo jobInfo) {
ReturnT<String> result = xxlJobService.add(jobInfo);
int id = Integer.valueOf(result.getContent());
xxlJobService.start(id);
return result;
}
// 重写数据校验的方法
@RequestMapping("/cronTriggerTime")
@ResponseBody
@PermissionLimit(limit = false)
public ReturnT<List<String>> cronTriggerTime(String scheduleType, String scheduleConf) {
XxlJobInfo paramXxlJobInfo = new XxlJobInfo();
paramXxlJobInfo.setScheduleType(scheduleType);
paramXxlJobInfo.setScheduleConf(scheduleConf);
List<String> result = new ArrayList<>();
try {
Date lastTime = new Date();
for (int i = 0; i < 5; i++) {
lastTime = JobScheduleHelper.generateNextValidTime(paramXxlJobInfo, lastTime);
if (lastTime != null) {
result.add(DateUtil.formatDateTime(lastTime));
} else {
break;
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
return new ReturnT<List<String>>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type") + I18nUtil.getString("system_unvalid")) + e.getMessage());
}
return new ReturnT<List<String>>(result);
}
构造调用 xxl-job 的项目
第一步
- 添加 pom.xml 文件
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>2020.0.4</spring-cloud.version>
<spring-cloud-alibaba.version>2021.1</spring-cloud-alibaba.version>
<spring-boot-dependencies.version>2.5.6</spring-boot-dependencies.version>
</properties>
<!--nacos consumer-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--xxl-job-->
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-job-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot-dependencies.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
第二步
- 添加配置文件
spring:
application:
name: springboot-Xxljob
nacos:
discovery:
server-addr: xxxx-xx-xx:8848
main:
allow-bean-definition-overriding: true
config:
job:
url: xxl-job-service
xxl:
job:
# 执行器通讯TOKEN,非空时启用
accessToken: ''
admin:
# 调度中心部署跟地址:如调度中心集群部署存在多个地址则用逗号分隔。执行器将会使用该地址进行"执行器心跳注册"和"任务结果回调"
addresses: http://127.0.0.1:8082/xxlJobAdmin/v1
executor:
# 执行器"AppName"和地址信息配置:AppName执行器心跳注册分组依据;地址信息用于"调度中心请求并触发任务"和"执行器注册"。执行器默认端口为9999,执行器IP默认为空表示自动获取IP,多网卡时可手动设置指定IP,该IP不会绑定Host仅作为通讯实用。单机部署多个执行器时,注意要配置不同执行器端口
appname: xxl-server
ip: ''
address: ''
# 执行器运行日志文件存储的磁盘位置,需要对该路径拥有读写权限
logpath: /data/applogs/xxl-job/jobhandler
# 执行器Log文件定期清理功能,指定日志保存天数,日志文件过期自动删除。限制至少保持3天,否则功能不生效;
logretentiondays: 30
port: 9999
第三步
- 定义 xxl-job 的配置类
@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);
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();
*/
}
第四步
- 定义 Feign 调用接口
@FeignClient(name = "${config.job.url}")
@Component
@RequestMapping("/xxlJobAdmin/v1")
public interface JobInfoClient {
/**
* CRON 数据校验
*
* @param scheduleType
* @param scheduleConf
* @return
*/
@GetMapping("/jobinfo/cronTriggerTime")
ReturnT<List<String>> cronTriggerTime(@RequestParam("scheduleType") String scheduleType, @RequestParam("scheduleConf") String scheduleConf);
/**
* 新增任务
*
* @param jobInfo
* @return
*/
@PostMapping("/jobinfo/addJob")
ReturnT<String> addJob(@RequestBody XxlJobInfo jobInfo);
/**
* 更新任务
*
* @param jobInfo
* @return
*/
@PutMapping("/jobinfo/updateJob")
ReturnT<String> updateJob(@RequestBody XxlJobInfo jobInfo);
/**
* 删除任务
*
* @param id
* @return
*/
@DeleteMapping("/jobinfo/removeJob")
ReturnT<String> removeJob(@RequestParam("id") Integer id);
/**
* 停止任务
*
* @param id
* @return
*/
@Transactional
@PutMapping("/jobinfo/stopJob")
ReturnT<String> pauseJob(@RequestParam("id") Integer id);
/**
* 开始任务
*
* @param id
* @return
*/
@Transactional
@PutMapping("/jobinfo/startJob")
ReturnT<String> startJob(@RequestParam("id") Integer id);
/**
* 添加并开始任务
*
* @param jobInfo
* @return
*/
@PostMapping("/jobinfo/addAndStart")
ReturnT<String> addAndStart(@RequestBody XxlJobInfo jobInfo);
}
第五步
- 定义运行的 Hander
/**
* XxlJob开发示例(Bean模式)
* <p>
* 开发步骤:
* 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
*/
@Slf4j
@Component
public class SampleXxlJob {
private String str = "XXL-JOB,参数:";
private static ExecutorService pool;
/**
* 这里引入多线程
* @PostConstruct 的作用是在项目启动时执行这个方法
* maximumPoolSize 设置为 2 ,拒绝策略为 AbortPolicy 策略,直接抛出异常
*/
@PostConstruct
public void init() {
pool = new ThreadPoolExecutor(1, 2, 1000, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
}
/**
* 1、简单任务示例(Bean模式)
*/
@XxlJob("demoJobHandler")
public void demoJobHandler() {
String command = XxlJobHelper.getJobParam();
XxlJobHelper.log(str + command);
String[] split = command.split("-");
if (split.length != 2) {
XxlJobHelper.log("参数错误---" + command);
} else {
Integer taskId = Integer.parseInt(split[0]);
Integer jobId = Integer.parseInt(split[1]);
/**
* 处理业务的代码
*/
}
}
/**
* 2、分片广播任务
*/
@XxlJob("shardingJobHandler")
public void shardingJobHandler() {
// 分片参数
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);
}
}
}
/**
* 4、跨平台Http任务
* 参数示例:
* "url: http://www.baidu.com\n" +
* "method: get\n" +
* "data: content\n";
*/
@XxlJob("httpJobHandler")
public void httpJobHandler() {
// param parse
String param = XxlJobHelper.getJobParam();
if (param == null || param.trim().length() == 0) {
XxlJobHelper.log("param[" + param + "] invalid.");
XxlJobHelper.handleFail();
return;
}
String[] httpParams = param.split("\n");
String url = null;
String method = null;
String data = null;
for (String httpParam : httpParams) {
if (httpParam.startsWith("url:")) {
url = httpParam.substring(httpParam.indexOf("url:") + 4).trim();
}
if (httpParam.startsWith("method:")) {
method = httpParam.substring(httpParam.indexOf("method:") + 7).trim().toUpperCase();
}
if (httpParam.startsWith("data:")) {
data = httpParam.substring(httpParam.indexOf("data:") + 5).trim();
}
}
// param valid
if (url == null || url.trim().length() == 0) {
XxlJobHelper.log("url[" + url + "] invalid.");
XxlJobHelper.handleFail();
return;
}
if (method == null || !Arrays.asList("GET", "POST").contains(method)) {
XxlJobHelper.log("method[" + method + "] invalid.");
XxlJobHelper.handleFail();
return;
}
boolean isPostMethod = method.equals("POST");
// request
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
try {
// connection
URL realUrl = new URL(url);
connection = (HttpURLConnection) realUrl.openConnection();
// connection setting
connection.setRequestMethod(method);
connection.setDoOutput(isPostMethod);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setReadTimeout(5 * 1000);
connection.setConnectTimeout(3 * 1000);
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.setRequestProperty("Accept-Charset", "application/json;charset=UTF-8");
// do connection
connection.connect();
// data
if (isPostMethod && data != null && data.trim().length() > 0) {
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.write(data.getBytes("UTF-8"));
dataOutputStream.flush();
dataOutputStream.close();
}
// valid StatusCode
int statusCode = connection.getResponseCode();
if (statusCode != 200) {
throw new RuntimeException("Http Request StatusCode(" + statusCode + ") Invalid.");
}
// result
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
StringBuilder result = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
String responseMsg = result.toString();
XxlJobHelper.log(responseMsg);
return;
} catch (Exception e) {
XxlJobHelper.log(e);
XxlJobHelper.handleFail();
return;
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (Exception e2) {
XxlJobHelper.log(e2);
}
}
}
/**
* 5、生命周期任务示例:任务初始化与销毁时,支持自定义相关逻辑;
*/
@XxlJob(value = "demoJobHandler2", init = "init", destroy = "destroy")
public void demoJobHandler2() {
XxlJobHelper.log(str);
}
public void destroy() {
log.info("destory");
}
}
第六步
- 业务调用
@RestController
@Slf4j
@RequestMapping("/quart")
public class QuartzController {
@Resource
private JobInfoClient jobInfoClient;
/**
* 执行器名称,这个值默认在配置项中配置
*/
@Value("${xxl.job.executor.appname}")
private String appname;
/**
* 这里添加一个例子说明如何调用 xxl-job 对应的方法
* 具体使用的时候,需要根据实际的使用情况封装对应的参数
*/
@PostMapping("/addTask")
public void addTask() {
/**
* 定义参数的值
* handler 的值就是 SampleXxlJob 类对应方法的名称注解
* 在后续的业务调用中,只需要在创建新的 Job 时,传入对应的参数即可执行对应 Hanlder 里面的任务
*/
String name = "这是测试Demo";
String param = "这是Task的参数";
String handler = "demoJobHandler";
ReturnT<Integer> groupId = jobInfoClient.getGroupId(appname);
Integer infoClientId = jobInfoClient.getId(name);
XxlJobInfo xxlJobInfo = XxlJobInfo.taskJob(groupId.getContent(), name, null, null, handler, param, 0);
if (ObjectUtils.isEmpty(infoClientId)) {
// 添加 xxl-job 的任务
ReturnT<String> returnT = jobInfoClient.addJob(xxlJobInfo);
if (returnT.getCode() != 200) {
log.error("调度任务创建失败,传入的数据为:{}", xxlJobInfo);
return;
}
}
}
}
第七步
- 启动类增加注解
@SpringBootApplication
@EnableFeignClients
public class SpringbootQuartzApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootQuartzApplication.class, args);
}
}