目录
- 前言
- 1. 基本知识
- 2. Demo
- 3. 实战
前言
可视化任务调度
可视化配置
1. 基本知识
在Java中,分布式任务调度框架 XXL-Job 是一个开源的分布式任务调度平台,用于实现分布式系统中的定时任务调度和分布式任务执行。
下面是关于XXL-Job的一些概念、功能、作用以及优缺点的介绍
概念 | 功能 | 作用 | 优点 |
---|---|---|---|
1.调度中心(Admin): 提供任务管理、调度管理、执行器管理等功能的中心节点。 2.执行器(Executor): 执行实际业务逻辑的节点,通过注册到调度中心参与任务调度。 3.任务(Job): 由调度中心定时触发并发送到执行器执行的业务逻辑。 | 1.分布式任务调度: 实现在分布式环境下的任务调度,支持大规模任务集群管理。 2.任务流程管理: 支持任务的流程依赖关系,可以定义任务的执行流程。 3.动态任务调度: 支持动态添加、修改、删除任务,无需重启服务。 4.任务日志与监控: 提供任务执行日志和监控功能,方便排查问题和性能监控。 | 1.定时任务调度: 提供可靠的定时任务调度功能,适用于需要周期性执行任务的场景。 2.分布式任务协调: 在分布式环境下,协调各个执行器节点执行任务,实现任务的分布式执行。 | 1.易用性: 提供可视化的任务管理界面,方便用户管理和监控任务。 2.可扩展性: 支持集群部署,可以轻松扩展任务执行能力。 3.动态调度: 支持动态添加、修改、删除任务,无需停止服务。 |
2. Demo
此处的Demo只是讲解一个流程,方便大家熟知
-
创建任务
:
在调度中心的管理界面上创建一个新的定时任务,设置任务的执行逻辑和调度规则。 -
注册执行器
:
启动一个执行器,并注册到调度中心,执行器会定期向调度中心拉取任务并执行。 -
执行任务
:
调度中心按照设定的规则触发任务,任务被分配到某个执行器上执行。 -
查看日志
:
在调度中心界面上查看任务执行日志,检查任务是否按照预期执行。
项目中引入 XXL-Job 的依赖:
<dependencies><!-- XXL-Job core --><dependency><groupId>com.xxl-job</groupId><artifactId>xxl-job-core</artifactId><version>2.3.0</version></dependency><!-- 其他依赖... -->
</dependencies>
创建一个简单的任务执行器类:
import com.xxl.job.core.executor.XxlJobExecutor;public class XxlJobExecutorExample {public static void main(String[] args) {// 1. 初始化执行器XxlJobExecutor executor = new XxlJobExecutor();executor.init();// 2. 启动执行器executor.start();// 3. 在执行器中注册任务,具体任务逻辑在 JobHandler 中实现// 可以通过调度中心创建任务,并在 JobHandler 中编写具体业务逻辑// 4. 停止执行器// executor.destroy();}
}
创建一个简单的任务处理器类 MyJobHandler:
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;public class MyJobHandler {@XxlJob("myJobHandler")public void myJobHandler() {// 业务逻辑实现XxlJobHelper.log("Hello, XXL-Job! This is a simple job.");}
}
在 myJobHandler 方法上使用 @XxlJob
注解标注,该方法即为需要定时执行的任务逻辑。
3. 实战
本身xxl-job开源,所以上述的demo例子只是一个大致流程,具体可看下方的操作:
对于XXL-Job为开源项目,通过github地址下载即可:XXL-Job的github地址
下载完成之后的界面如下:
- 导入sql脚本
导入sql执行的语句,路径位于:/xxl-job/doc/db/tables_xxl_job.sql
2.配置调度中心,修改配置文件,路径位于:/xxl-job/xxl-job-admin/src/main/resources/application.properties
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
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
配置完成之后,注意端口不要冲突,启动路径:xxl-job-admin/src/main/java/com/xxl/job/admin/XxlJobAdminApplication.java
访问其url:http://localhost:8080/xxl-job-admin
3. 配置执行器
先导入依赖包:
<dependency><groupId>com.xuxueli</groupId><artifactId>xxl-job-core</artifactId><version>2.2.0</version>
</dependency>
对应将该xxl-job-executor-samples/xxl-job-executor-sample-springboot/src/main/resources/application.properties
配置文件配置到springboot项目中:(注意修改配置)
# web port
server.port=8081
# no web
#spring.main.web-environment=false# log config
logging.config=classpath:logback.xml### xxl-job admin address list, such as "http://address" or "http://address01,http://address02"
xxl.job.admin.addresses=http://127.0.0.1:8080/xxl-job-admin### xxl-job, access token
xxl.job.accessToken=default_token### xxl-job executor appname
xxl.job.executor.appname=xxl-job-executor-sample
### 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
4. 配置执行器:(可全部拷贝)
package com.xxl.job.executor.core.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;/*** 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;@Beanpublic 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();*/}
5. 创建任务,之后执行springboot启动类
package com.xxl.job.executor.service.jobhandler;import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.concurrent.TimeUnit;/*** 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
public class SampleXxlJob {private static Logger logger = LoggerFactory.getLogger(SampleXxlJob.class);/*** 1、简单任务示例(Bean模式)*/@XxlJob("demoJobHandler")public void demoJobHandler() throws Exception {XxlJobHelper.log("码农研究僧.");// default success}/*** 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);}}}/*** 3、命令行任务*/@XxlJob("commandJobHandler")public void commandJobHandler() throws Exception {String command = XxlJobHelper.getJobParam();int exitValue = -1;BufferedReader bufferedReader = null;try {// command processProcessBuilder processBuilder = new ProcessBuilder();processBuilder.command(command);processBuilder.redirectErrorStream(true);Process process = processBuilder.start();//Process process = Runtime.getRuntime().exec(command);BufferedInputStream bufferedInputStream = new BufferedInputStream(process.getInputStream());bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));// command logString line;while ((line = bufferedReader.readLine()) != null) {XxlJobHelper.log(line);}// command exitprocess.waitFor();exitValue = process.exitValue();} catch (Exception e) {XxlJobHelper.log(e);} finally {if (bufferedReader != null) {bufferedReader.close();}}if (exitValue == 0) {// default success} else {XxlJobHelper.handleFail("command exit value("+exitValue+") is failed");}}/*** 4、跨平台Http任务* 参数示例:* "url: http://www.baidu.com\n" +* "method: get\n" +* "data: content\n";*/@XxlJob("httpJobHandler")public void httpJobHandler() throws Exception {// param parseString 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 validif (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");// requestHttpURLConnection connection = null;BufferedReader bufferedReader = null;try {// connectionURL realUrl = new URL(url);connection = (HttpURLConnection) realUrl.openConnection();// connection settingconnection.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 connectionconnection.connect();// dataif (isPostMethod && data!=null && data.trim().length()>0) {DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());dataOutputStream.write(data.getBytes("UTF-8"));dataOutputStream.flush();dataOutputStream.close();}// valid StatusCodeint statusCode = connection.getResponseCode();if (statusCode != 200) {throw new RuntimeException("Http Request StatusCode(" + statusCode + ") Invalid.");}// resultbufferedReader = 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() throws Exception {XxlJobHelper.log("XXL-JOB, Hello World.");}public void init(){logger.info("init");}public void destroy(){logger.info("destroy");}}
6. 配置后台界面
在操作界面中添加执行器管理:
在任务管理中添加任务
配置为BEAN,并且JobHandler为对应Java的注解@XxlJob("xxxx")
:
配置完成之后可点开执行日志,看到日志的输出: