SpringBoot整合Xxl-Job的完整步驟記錄
一、下載Xxl-Job源代碼并導(dǎo)入本地并運(yùn)行
Github地址:
https://github.com/xuxueli/xxl-job
中文文檔地址:
https://www.xuxueli.com/xxl-job/
1.使用Idea或Eclipse導(dǎo)入
2.執(zhí)行sql腳本(紅色標(biāo)記處)

3.運(yùn)行xxl-job-admin(xxl-job后臺(tái)管理,主要方便管理各種各樣的任務(wù))
注意:在運(yùn)行之前,需要把2的sql腳本執(zhí)行完畢,并修改數(shù)據(jù)庫(kù)連接池。
正常啟動(dòng),訪問(wèn)地址為:http://localhost:8080/xxl-job-admin
效果圖,如下所示:

用戶名默認(rèn)為admin
密碼為123456
輸入后,進(jìn)入這個(gè)界面,如圖:

這樣就表示Xxl-Job成功運(yùn)行了。確保運(yùn)行沒(méi)問(wèn)題后,就可以開始下一步。
二、添加執(zhí)行器(Xxl-Job源代碼就一個(gè)Example,可以復(fù)用過(guò)來(lái),你也可以選擇自己新建項(xiàng)目,新建項(xiàng)目可以在Xxl-Job基礎(chǔ)上,也可以放在其它項(xiàng)目中)
1.新建一個(gè)Maven項(xiàng)目,命名為blog-xxl-job。
2.導(dǎo)入Maven依賴
<!-- https://mvnrepository.com/artifact/com.xuxueli/xxl-job-core --> <dependency> <groupId>com.xuxueli</groupId> <artifactId>xxl-job-core</artifactId> <version>2.2.0</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
3.新建application.yml配置文件并添加如下內(nèi)容
#eureka eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/ # 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= ### xxl-job executor appname xxl.job.executor.appname=blog-xxl-job-executor ### 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
可以不用eureka,這里我的項(xiàng)目中用到eureka所以增加該配置。
增加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>
4.編寫Application類
package com.springcloud.blog.job.execute;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableEurekaClient
@EnableDiscoveryClient
@SpringBootApplication
public class BlogXxlJobExecutorApplication {
public static void main(String[] args) {
SpringApplication.run(BlogXxlJobExecutorApplication.class, args);
}
}
5.編寫Job執(zhí)行器
package com.springcloud.blog.job.execute.jobhandler;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
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開發(fā)示例(Bean模式)
* <p>
* 開發(fā)步驟:
* 1、在Spring Bean實(shí)例中,開發(fā)Job方法,方式格式要求為 "public ReturnT<String> execute(String param)"
* 2、為Job方法添加注解 "@XxlJob(value="自定義jobhandler名稱", init = "JobHandler初始化方法", destroy = "JobHandler銷毀方法")",注解value值對(duì)應(yīng)的是調(diào)度中心新建任務(wù)的JobHandler屬性的值。
* 3、執(zhí)行日志:需要通過(guò) "XxlJobLogger.log" 打印執(zhí)行日志;
*
* @author xuxueli 2019-12-11 21:52:51
*/
@Component
public class SampleXxlJob {
private static Logger logger = LoggerFactory.getLogger(SampleXxlJob.class);
/**
* 1、簡(jiǎn)單任務(wù)示例(Bean模式)
*/
@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;
}
/**
* 2、分片廣播任務(wù)
*/
@XxlJob("shardingJobHandler")
public ReturnT<String> shardingJobHandler(String param) throws Exception {
// 分片參數(shù)
ShardingUtil.ShardingVO shardingVO = ShardingUtil.getShardingVo();
XxlJobLogger.log("分片參數(shù):當(dāng)前分片序號(hào) = {}, 總分片數(shù) = {}", shardingVO.getIndex(), shardingVO.getTotal());
// 業(yè)務(wù)邏輯
for (int i = 0; i < shardingVO.getTotal(); i++) {
if (i == shardingVO.getIndex()) {
XxlJobLogger.log("第 {} 片, 命中分片開始處理", i);
} else {
XxlJobLogger.log("第 {} 片, 忽略", i);
}
}
return ReturnT.SUCCESS;
}
/**
* 3、命令行任務(wù)
*/
@XxlJob("commandJobHandler")
public ReturnT<String> commandJobHandler(String param) throws Exception {
String command = param;
int exitValue = -1;
BufferedReader bufferedReader = null;
try {
// command process
Process process = Runtime.getRuntime().exec(command);
BufferedInputStream bufferedInputStream = new BufferedInputStream(process.getInputStream());
bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));
// command log
String line;
while ((line = bufferedReader.readLine()) != null) {
XxlJobLogger.log(line);
}
// command exit
process.waitFor();
exitValue = process.exitValue();
} catch (Exception e) {
XxlJobLogger.log(e);
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}
if (exitValue == 0) {
return IJobHandler.SUCCESS;
} else {
return new ReturnT<String>(IJobHandler.FAIL.getCode(), "command exit value(" + exitValue + ") is failed");
}
}
/**
* 4、跨平臺(tái)Http任務(wù)
* 參數(shù)示例:
* "url: http://www.baidu.com\n" +
* "method: get\n" +
* "data: content\n";
*/
@XxlJob("httpJobHandler")
public ReturnT<String> httpJobHandler(String param) throws Exception {
// param parse
if (param == null || param.trim().length() == 0) {
XxlJobLogger.log("param[" + param + "] invalid.");
return ReturnT.FAIL;
}
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) {
XxlJobLogger.log("url[" + url + "] invalid.");
return ReturnT.FAIL;
}
if (method == null || !Arrays.asList("GET", "POST").contains(method)) {
XxlJobLogger.log("method[" + method + "] invalid.");
return ReturnT.FAIL;
}
// 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(true);
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 (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();
XxlJobLogger.log(responseMsg);
return ReturnT.SUCCESS;
} catch (Exception e) {
XxlJobLogger.log(e);
return ReturnT.FAIL;
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (Exception e2) {
XxlJobLogger.log(e2);
}
}
}
/**
* 5、生命周期任務(wù)示例:任務(wù)初始化與銷毀時(shí),支持自定義相關(guān)邏輯;
*/
@XxlJob(value = "demoJobHandler2", init = "init", destroy = "destroy")
public ReturnT<String> demoJobHandler2(String param) throws Exception {
XxlJobLogger.log("XXL-JOB, Hello World.");
return ReturnT.SUCCESS;
}
public void init() {
logger.info("init");
}
public void destroy() {
logger.info("destory");
}
}
6.增加X(jué)xlJobConfig配置類
package com.springcloud.blog.job.execute.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;
@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;
}
}
三、結(jié)合Xxl-Job后臺(tái)系統(tǒng)增加定時(shí)任務(wù)
1.配置執(zhí)行器

執(zhí)行器地址為(與blog-xxl-job中application.yml配置文件里的執(zhí)行器地址需要保持一致,否則會(huì)注冊(cè)失敗,導(dǎo)致任務(wù)執(zhí)行不了:

2.添加任務(wù)

3.任務(wù)執(zhí)行成功的標(biāo)志

四、為什么選擇Xxl-Job
當(dāng)初選擇使用Xxl-Job有這么幾個(gè)原因:
第一、團(tuán)隊(duì)里有好幾個(gè)人上一家公司或上上家公司用過(guò)。
第二、這個(gè)生態(tài)比較豐富且開源。
第三、確實(shí)非常容易上手且輕量化(輕量化的一個(gè)體現(xiàn)就是非侵入式)
到此這篇關(guān)于SpringBoot整合Xxl-Job的文章就介紹到這了,更多相關(guān)SpringBoot整合Xxl-Job內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot集成XXL-JOB實(shí)現(xiàn)靈活控制的分片處理方案
- xxl-job定時(shí)任務(wù)配置應(yīng)用及添加到springboot項(xiàng)目中實(shí)現(xiàn)動(dòng)態(tài)API調(diào)用
- SpringBoot集成xxl-job實(shí)現(xiàn)超牛的定時(shí)任務(wù)的步驟詳解
- SpringBoot部署xxl-job方法詳細(xì)講解
- springboot整合xxl-job實(shí)現(xiàn)分布式定時(shí)任務(wù)的過(guò)程
- 分布式調(diào)度XXL-Job整合Springboot2.X實(shí)戰(zhàn)操作過(guò)程(推薦)
- SpringBoot整合Xxl-job實(shí)現(xiàn)定時(shí)任務(wù)的全過(guò)程
- springboot整合 xxl-job及使用步驟
相關(guān)文章
Hibernate延遲加載原理與實(shí)現(xiàn)方法
這篇文章主要介紹了Hibernate延遲加載原理與實(shí)現(xiàn)方法,較為詳細(xì)的分析了Hibernate延遲加載的概念,原理與相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2016-03-03
Maven打包所有依賴到一個(gè)可執(zhí)行jar中遇到的問(wèn)題
這篇文章主要給大家介紹了關(guān)于Maven打包所有依賴到一個(gè)可執(zhí)行jar中遇到的問(wèn)題,將依賴打入jar包,由于maven管理了所有的依賴,所以將項(xiàng)目的代碼和依賴打成一個(gè)包對(duì)它來(lái)說(shuō)是順理成章的功能,需要的朋友可以參考下2023-10-10
數(shù)據(jù)庫(kù)連接池c3p0配置_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要為大家詳細(xì)介紹了數(shù)據(jù)庫(kù)連接池c3p0配置的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08
SpringBoot項(xiàng)目整合MybatisPlus并使用SQLite作為數(shù)據(jù)庫(kù)的過(guò)程
SQLite是一個(gè)緊湊的庫(kù),啟用所有功能后,庫(kù)大小可以小于 750KiB, 具體取決于目標(biāo)平臺(tái)和編譯器優(yōu)化設(shè)置, 內(nèi)存使用量和速度之間需要權(quán)衡,這篇文章主要介紹了SpringBoot項(xiàng)目整合MybatisPlus并使用SQLite作為數(shù)據(jù)庫(kù),需要的朋友可以參考下2024-07-07
Spring框架實(shí)現(xiàn)滑動(dòng)驗(yàn)證碼功能的代碼示例
之前項(xiàng)目需要在驗(yàn)證碼模塊,增加滑動(dòng)驗(yàn)證碼,用來(lái)給手機(jī)端使用的,大概看了下,主要方法就是將圖片切割,然后記住偏移量,進(jìn)行滑動(dòng),所以本文給大家介紹了Spring框架實(shí)現(xiàn)滑動(dòng)驗(yàn)證碼功能的方法示例,需要的朋友可以參考下2024-07-07
Springboot?application.yml配置文件拆分方式
這篇文章主要介紹了Springboot?application.yml配置文件拆分方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05

