Spring Boot 整合 xxl-job 保姆级教程!
在Spring Boot中整合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=你的XXL-JOB-ADMIN地址
# xxl.job executor appname
xxl.job.executor.appname=你的执行器名称
# xxl.job executor ip
xxl.job.executor.ip=自动获取可以为空
# xxl.job executor port
xxl.job.executor.port=你的执行器端口
# xxl.job access token
xxl.job.accessToken=你的访问令牌
# xxl.job executor logpath
xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler
# xxl.job executor logretentiondays
xxl.job.executor.logretentiondays=30
- 创建一个JobHandler类实现
com.xxl.job.core.handler.IJobHandler
接口:
@Component
public class SampleXxlJob implements IJobHandler {
@Override
public ReturnT<String> execute(String param) throws Exception {
// 你的任务逻辑
XxlJobLogger.log("这是一个XXL-JOB的示例");
return ReturnT.SUCCESS;
}
}
- 配置执行器Bean:
@Configuration
public class XxlJobConfig {
@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.accessToken}")
private String accessToken;
@Bean
public XxlJobExecutor xxlJobExecutor() {
XxlJobExecutor xxlJobExecutor = new XxlJobExecutor();
// 设置admin地址
xxlJobExecutor.setAdminAddresses(adminAddresses);
// 设置执行器相关信息
xxlJobExecutor.setAppName(appName);
xxlJobExecutor.setIp(ip);
xxlJobExecutor.setPort(port);
xxlJobExecutor.setAccessToken(accessToken);
return xxlJobExecutor;
}
}
- 在Spring Boot启动类上添加
@EnableXxlJob
注解启用XXL-JOB:
@SpringBootApplication
@EnableXxlJob
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
- 在XXL-JOB的管理界面配置你的任务,指定执行器,并且设置相应的JobHandler类名称。
以上步骤完成后,你的Spring Boot应用就可以通过XXL-JOB执行定时任务了。
评论已关闭