springboot整合xxl-job项目使用(含完整代码)
在Spring Boot项目中整合XXL-JOB,首先需要添加XXL-JOB的依赖,然后配置相关的配置文件,并初始化调度中心。
- 添加XXL-JOB的依赖到
pom.xml
:
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-job-core</artifactId>
<version>版本号</version>
</dependency>
- 在
application.properties
或application.yml
中配置XXL-JOB:
# xxl-job admin address
xxl.job.admin.addresses=http://127.0.0.1:8080/xxl-job-admin
# xxl-job executor address
xxl.job.executor.ip=127.0.0.1
xxl.job.executor.port=9999
# xxl-job executor appname
xxl.job.executor.appname=xxl-job-executor-sample
# xxl-job executor logpath
xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler
# xxl-job executor logretentiondays
xxl.job.executor.logretentiondays=30
- 创建配置类初始化XXL-JOB:
@Configuration
public class XxlJobConfig {
private static Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);
@Value("${xxl.job.admin.addresses}")
private String adminAddresses;
@Value("${xxl.job.executor.appname}")
private String appName;
@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.setIp(ip);
xxlJobSpringExecutor.setPort(port);
xxlJobSpringExecutor.setLogPath(logPath);
xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);
return xxlJobSpringExecutor;
}
}
- 创建任务处理器:
@Component
public class SampleXxlJob {
@XxlJob("demoJobHandler")
public void execute() throws Exception {
// 任务逻辑
XxlJobHelper.log("这是一个示例任务");
// 任务执行完毕返回成功
XxlJobHelper.success();
}
}
确保你的Spring Boot应用包含了上述配置后,启动应用,XXL-JOB的执行器会自动注册到调度中心,并且可以执行定时任务。
注意:在实际使用时,需要替换版本号
为你所使用的XXL-JOB的版本,并且根据实
评论已关闭