依赖
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-job-core</artifactId>
<version>2.2.0</version>
</dependency>
配置文件
xxl:
job:
accessToken:
admin:
# xxl-job admin地址,多个admin地址用,分开
addresses: http://192.168.200.128:8080/xxl-job-admin
executor:
# 自定义执行器名称,一般为该微服务名称
appname: test-service
address:
ip:
# 自定义与xxl-job的通信端口;单机部署多个执行器时,注意要配置不同执行器端口
port: 9999
# 执行日志保存的位置,需要对该路径拥有读写权限;为空则使用默认路径
logpath: /data/applogs/xxl-job/testhandler
# 执行日志保留天数,大于等于3时生效; 否则, 如-1, 关闭自动清理功能
logretentiondays: 30
配置类
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@Slf4j
public class XxlJobConfig {
@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() {
log.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;
}
}
新建一个job
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class TestJob {
@XxlJob("testHandler")
public ReturnT<String> testHandler(String param) throws Exception {
try {
log.info("测试xxl-job");
// 执行逻辑
// return ReturnT.SUCCESS.setMsg("任务执行成功!");
return ReturnT.SUCCESS_CODE;
} catch (Exception e) {
// return ReturnT.FAIL.setMsg("任务执行失败!");
return ReturnT.FAIL_CODE;
}
}
}
在xxl-job-admin里新建执行器test-service
在xxl-job-admin里配置任务
即可