xxl-job在 Spring Boot 項(xiàng)目中的完整配置指南(最新整理)
一、Maven依賴配置
<!-- XXL-Job 核心依賴 -->
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-job-core</artifactId>
<version>2.4.0</version>
</dependency>
<!-- Spring Boot Starter(推薦) -->
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-job-core</artifactId>
<version>2.4.0</version>
</dependency>二、配置文件詳解
1. application.yml/application.properties 配置
# XXL-Job 執(zhí)行器配置
xxl:
job:
# 調(diào)度中心部署地址 [選填]:調(diào)度中心地址,如:http://127.0.0.1:8080/xxl-job-admin
admin:
addresses: http://127.0.0.1:8080/xxl-job-admin
# 執(zhí)行器通訊TOKEN [選填]:非空時(shí)啟用,與調(diào)度中心配置保持一致
accessToken: default_token
# 執(zhí)行器配置
executor:
# 執(zhí)行器AppName [選填]:執(zhí)行器心跳注冊(cè)分組依據(jù),為空則關(guān)閉自動(dòng)注冊(cè)
appname: xxl-job-executor-sample
# 執(zhí)行器IP [選填]:默認(rèn)為空表示自動(dòng)獲取IP
# ip: 192.168.1.100
# 執(zhí)行器端口號(hào) [選填]:小于等于0則自動(dòng)獲取,默認(rèn)端口為9999
port: 9999
# 執(zhí)行器運(yùn)行日志文件存儲(chǔ)路徑 [選填]:需要配置權(quán)限
logpath: /data/applogs/xxl-job/jobhandler
# 執(zhí)行器日志文件保存天數(shù) [選填]:過(guò)期日志自動(dòng)清理,限制值大于等于3
logretentiondays: 30
# 執(zhí)行器注冊(cè)方式 [選填]:默認(rèn)自動(dòng)注冊(cè),支持手動(dòng)錄入
# address: http://127.0.0.1:9999/Properties格式:
# XXL-Job 配置 xxl.job.admin.addresses=http://127.0.0.1:8080/xxl-job-admin xxl.job.accessToken=default_token xxl.job.executor.appname=xxl-job-executor-sample xxl.job.executor.port=9999 xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler xxl.job.executor.logretentiondays=30
三、Spring Boot配置類
1. 基礎(chǔ)配置類
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;
}
}2. 多環(huán)境配置支持
@Configuration
@ConfigurationProperties(prefix = "xxl.job")
@Data
public class XxlJobProperties {
/**
* 是否啟用XXL-Job
*/
private boolean enabled = true;
/**
* 調(diào)度中心配置
*/
private Admin admin = new Admin();
/**
* 執(zhí)行器配置
*/
private Executor executor = new Executor();
@Data
public static class Admin {
private String addresses;
}
@Data
public static class Executor {
private String appname;
private String ip;
private Integer port;
private String logPath;
private Integer logRetentionDays;
private String address;
}
@Bean
@ConditionalOnProperty(prefix = "xxl.job", name = "enabled", havingValue = "true")
public XxlJobSpringExecutor xxlJobExecutor(XxlJobProperties xxlJobProperties) {
XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
// 設(shè)置配置項(xiàng)
xxlJobSpringExecutor.setAdminAddresses(xxlJobProperties.getAdmin().getAddresses());
xxlJobSpringExecutor.setAppname(xxlJobProperties.getExecutor().getAppname());
xxlJobSpringExecutor.setIp(xxlJobProperties.getExecutor().getIp());
xxlJobSpringExecutor.setPort(xxlJobProperties.getExecutor().getPort());
xxlJobSpringExecutor.setLogPath(xxlJobProperties.getExecutor().getLogPath());
xxlJobSpringExecutor.setLogRetentionDays(xxlJobProperties.getExecutor().getLogRetentionDays());
xxlJobSpringExecutor.setAddress(xxlJobProperties.getExecutor().getAddress());
return xxlJobSpringExecutor;
}
}四、任務(wù)處理器配置
1. Bean模式(推薦)
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class SampleXxlJob {
private static final Logger logger = LoggerFactory.getLogger(SampleXxlJob.class);
/**
* 簡(jiǎn)單任務(wù)示例
*/
@XxlJob("demoJobHandler")
public void demoJobHandler() throws Exception {
logger.info("XXL-JOB, Hello World.");
// 模擬任務(wù)執(zhí)行
for (int i = 0; i < 5; i++) {
logger.info("beat at:" + i);
Thread.sleep(1000);
}
// 默認(rèn)執(zhí)行結(jié)果
// return ReturnT.SUCCESS;
}
/**
* 帶參數(shù)的任務(wù)
*/
@XxlJob("paramJobHandler")
public ReturnT<String> paramJobHandler(String param) throws Exception {
logger.info("接收參數(shù): {}", param);
// 業(yè)務(wù)邏輯處理
if (param == null || param.trim().length() == 0) {
return new ReturnT<>(ReturnT.FAIL_CODE, "參數(shù)不能為空");
}
return ReturnT.SUCCESS;
}
/**
* 分片廣播任務(wù)
*/
@XxlJob("shardingJobHandler")
public void shardingJobHandler() throws Exception {
// 分片參數(shù)
ShardingUtil.ShardingVO shardingVO = ShardingUtil.getShardingVo();
logger.info("分片參數(shù):當(dāng)前分片序號(hào) = {}, 總分片數(shù) = {}",
shardingVO.getIndex(), shardingVO.getTotal());
// 分片處理邏輯
List<String> dataList = fetchData();
for (int i = 0; i < dataList.size(); i++) {
// 取模分片
if (i % shardingVO.getTotal() == shardingVO.getIndex()) {
processItem(dataList.get(i));
}
}
}
/**
* 初始化方法(可選)
*/
@XxlJob(value = "demoJobHandler", init = "init", destroy = "destroy")
public void demoJobHandler2() throws Exception {
logger.info("任務(wù)執(zhí)行...");
}
public void init() {
logger.info("任務(wù)初始化...");
}
public void destroy() {
logger.info("任務(wù)銷毀...");
}
}2. GLUE模式配置
/**
* GLUE(Java)模式,任務(wù)在調(diào)度中心編寫(xiě)代碼
* 執(zhí)行器只需要配置以下空方法
*/
@Component
public class GlueJob {
@XxlJob("glueJavaJobHandler")
public ReturnT<String> glueJavaJobHandler(String param) throws Exception {
// GLUE代碼在調(diào)度中心管理平臺(tái)編寫(xiě)和維護(hù)
// 執(zhí)行器只需要提供空方法即可
return ReturnT.SUCCESS;
}
}五、高級(jí)配置
1. 自定義注冊(cè)策略
@Configuration
public class CustomXxlJobConfig extends XxlJobSpringExecutor {
@Override
public void start() throws Exception {
// 自定義初始化邏輯
logger.info(">>>>>>>>>>> xxl-job custom executor start.");
super.start();
}
@Override
public void destroy() {
// 自定義銷毀邏輯
logger.info(">>>>>>>>>>> xxl-job custom executor destroy.");
super.destroy();
}
@Override
public ReturnT<String> beat() {
// 自定義心跳檢測(cè)
ReturnT<String> beatResult = super.beat();
logger.info("Custom heartbeat result: {}", beatResult);
return beatResult;
}
}2. 任務(wù)執(zhí)行監(jiān)控
@Aspect
@Component
@Slf4j
public class JobExecutionMonitorAspect {
@Around("@annotation(xxlJob)")
public Object monitorJobExecution(ProceedingJoinPoint joinPoint, XxlJob xxlJob) throws Throwable {
String jobName = xxlJob.value();
long startTime = System.currentTimeMillis();
log.info("Job [{}] 開(kāi)始執(zhí)行", jobName);
try {
Object result = joinPoint.proceed();
long executionTime = System.currentTimeMillis() - startTime;
log.info("Job [{}] 執(zhí)行成功,耗時(shí):{}ms", jobName, executionTime);
// 可以記錄到數(shù)據(jù)庫(kù)或發(fā)送監(jiān)控報(bào)警
recordJobExecution(jobName, true, executionTime);
return result;
} catch (Exception e) {
long executionTime = System.currentTimeMillis() - startTime;
log.error("Job [{}] 執(zhí)行失敗,耗時(shí):{}ms,錯(cuò)誤:{}",
jobName, executionTime, e.getMessage(), e);
recordJobExecution(jobName, false, executionTime);
throw e;
}
}
private void recordJobExecution(String jobName, boolean success, long executionTime) {
// 記錄執(zhí)行記錄到數(shù)據(jù)庫(kù)
// JobExecutionRecord record = new JobExecutionRecord();
// record.setJobName(jobName);
// record.setSuccess(success);
// record.setExecutionTime(executionTime);
// record.setExecuteTime(new Date());
// jobExecutionService.save(record);
}
}六、多環(huán)境配置文件示例
1. application-dev.yml(開(kāi)發(fā)環(huán)境)
xxl:
job:
admin:
addresses: http://localhost:8080/xxl-job-admin
executor:
appname: xxl-job-executor-dev
port: 9999
logpath: ./logs/xxl-job/jobhandler
logretentiondays: 72. application-test.yml(測(cè)試環(huán)境)
xxl:
job:
admin:
addresses: http://test-xxl-job-admin:8080/xxl-job-admin
accessToken: test_token_123
executor:
appname: xxl-job-executor-test
port: 9999
logpath: /data/logs/xxl-job/jobhandler
logretentiondays: 303. application-prod.yml(生產(chǎn)環(huán)境)
xxl:
job:
admin:
addresses: http://prod-xxl-job-admin-01:8080/xxl-job-admin,http://prod-xxl-job-admin-02:8080/xxl-job-admin
accessToken: prod_secure_token_${RANDOM}
executor:
appname: xxl-job-executor-prod
ip: ${EXECUTOR_IP:}
port: ${EXECUTOR_PORT:9999}
logpath: /data/applogs/xxl-job/jobhandler
logretentiondays: 90七、常見(jiàn)問(wèn)題配置
1. 網(wǎng)絡(luò)隔離配置
xxl:
job:
admin:
addresses: ${XXL_JOB_ADMIN_URL:http://localhost:8080/xxl-job-admin}
executor:
appname: ${HOSTNAME:${spring.application.name:xxl-job-executor}}
# 使用內(nèi)網(wǎng)IP注冊(cè)
ip: ${INTRANET_IP:}
# 使用外網(wǎng)地址訪問(wèn)(如有NAT)
address: ${EXTERNAL_URL:}2. Docker容器配置
xxl:
job:
executor:
appname: ${HOSTNAME:xxl-job-executor}
# 自動(dòng)獲取IP
ip:
# 使用服務(wù)發(fā)現(xiàn)地址
address: ${SERVICE_URL:}
port: 99993. 安全配置
@Configuration
public class SecurityXxlJobConfig {
@Bean
public XxlJobSpringExecutor xxlJobExecutor() {
XxlJobSpringExecutor executor = new XxlJobSpringExecutor();
// 從安全配置中心獲取token
String accessToken = getAccessTokenFromVault();
executor.setAccessToken(accessToken);
// 其他配置...
return executor;
}
}八、項(xiàng)目結(jié)構(gòu)
src/main/java/ ├── com/example/job │ ├── config │ │ ├── XxlJobConfig.java # 主配置類 │ │ └── XxlJobProperties.java # 配置屬性類 │ ├── handler │ │ ├── DemoJobHandler.java # 示例任務(wù) │ │ ├── OrderJobHandler.java # 訂單相關(guān)任務(wù) │ │ └── ReportJobHandler.java # 報(bào)表任務(wù) │ ├── aspect │ │ └── JobMonitorAspect.java # 任務(wù)監(jiān)控切面 │ └── JobApplication.java # 啟動(dòng)類
九、注意事項(xiàng)
- 端口沖突:確保9999端口未被占用,或修改為其他端口
- 網(wǎng)絡(luò)連通:確保執(zhí)行器能訪問(wèn)調(diào)度中心地址
- 權(quán)限問(wèn)題:日志目錄需要有寫(xiě)入權(quán)限
- 注冊(cè)失?。簷z查appname是否在調(diào)度中心存在
- 版本兼容:調(diào)度中心和執(zhí)行器版本要保持一致
- 日志清理:定期清理過(guò)期日志,避免磁盤占滿
十、性能優(yōu)化建議
- 線程池配置:根據(jù)任務(wù)量調(diào)整線程池大小
- 日志優(yōu)化:使用異步日志,避免IO阻塞
- 連接池:配置合適的HTTP連接池參數(shù)
- 監(jiān)控告警:集成監(jiān)控系統(tǒng),實(shí)時(shí)監(jiān)控任務(wù)執(zhí)行狀態(tài)
- 高可用:部署多個(gè)執(zhí)行器實(shí)例,實(shí)現(xiàn)負(fù)載均衡
到此這篇關(guān)于xxl-job在 Spring Boot 項(xiàng)目中的完整配置指南(最新整理)的文章就介紹到這了,更多相關(guān)springboot xxl-job配置內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot集成XXL-JOB實(shí)現(xiàn)任務(wù)管理全流程
- springboot如何通過(guò)http動(dòng)態(tài)操作xxl-job任務(wù)
- Springboot整合x(chóng)xl-job實(shí)現(xiàn)動(dòng)態(tài)傳參
- springboot整合 xxl-job及使用步驟
- 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ù)的步驟詳解
- xxl-job的部署及springboot集成使用示例詳解
- SpringBoot部署xxl-job方法詳細(xì)講解
- SpringBoot整合Xxl-job實(shí)現(xiàn)定時(shí)任務(wù)的全過(guò)程
- SpringBoot整合Xxl-Job的完整步驟記錄
相關(guān)文章
兩種Eclipse部署動(dòng)態(tài)web項(xiàng)目方法
這篇文章主要介紹了兩種Eclipse部署動(dòng)態(tài)web項(xiàng)目方法,需要的朋友可以參考下2015-11-11
MybatisPlus實(shí)現(xiàn)真正批量插入的詳細(xì)步驟
在數(shù)據(jù)庫(kù)操作中,批量插入是提升效率的重要手段,MyBatis-Plus提供了多種批量插入方法,但默認(rèn)的saveBatch方法效率并不高,文章介紹了通過(guò)手動(dòng)拼接SQL、使用IService接口以及自定義insertBatchSomeColumn方法進(jìn)行優(yōu)化,以實(shí)現(xiàn)更高效的批量插入,并給出了性能優(yōu)化建議2024-10-10
RocketMQ4.5.X 實(shí)現(xiàn)修改生產(chǎn)者消費(fèi)者日志保存路徑
這篇文章主要介紹了RocketMQ4.5.X 實(shí)現(xiàn)修改生產(chǎn)者消費(fèi)者日志保存路徑方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
Mybatis 傳輸List的實(shí)現(xiàn)代碼
本文通過(guò)實(shí)例代碼給大家介紹了mybatis傳輸list的實(shí)現(xiàn)代碼,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下吧2017-09-09
Mybatis-plus分頁(yè)查詢不生效問(wèn)題排查全過(guò)程
最近寫(xiě)分頁(yè)的時(shí)候,遇到了分頁(yè)無(wú)法正常發(fā)揮作用的問(wèn)題,下面這篇文章主要給大家介紹了關(guān)于Mybatis-plus分頁(yè)查詢不生效問(wèn)題排查的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03
解決mybatis-plus新增數(shù)據(jù)自增ID變無(wú)序問(wèn)題
這篇文章主要介紹了解決mybatis-plus新增數(shù)據(jù)自增ID變無(wú)序問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。2023-07-07

