创建springboot工程
xxl-job-admin 为xxl-job控制中心 demo-job 执行器demo
集成xxl-job控制台
xxl-job官网 代码地址
下载xxl-job控制台代码与sql文件
将sql导入到我们的数据库
将xxl-job-admin导入我们的工程
修改其配置文件
改好之后 启动应用即可 访问 http://localhost:9090/xxl-job-admin 进入控制台 默认账号密码为 admin/123456 可在用户头像处修改 进入到这 控制台就启动成功了
集成xxl-job执行器配置
编写项目配置文件 application.yml
server:
port: 8080
xxl:
job:
admin-addresses: http://localhost:9090/xxl-job-admin
access-token:
executor:
appname: xxl-job-executor-sample
port: 9101
address:
ip:
logpath: ./logs/xxl-job
logretentiondays: 30
编写项目配置类 XxlJobProperties.java
@Data
@ConfigurationProperties(prefix = "xxl.job")
public class XxlJobProperties {
private String adminAddresses;
private String accessToken;
private Executor executor;
@Data
@NoArgsConstructor
public static class Executor {
private String appname;
private String address;
private String ip;
private int port;
private String logPath;
private int logRetentionDays;
}
}
XxlJobConfig.java
@Slf4j
@Configuration
@EnableConfigurationProperties(XxlJobProperties.class)
@AllArgsConstructor
public class XxlJobConfig {
private final XxlJobProperties xxlJobProperties;
@Bean
public XxlJobSpringExecutor xxlJobExecutor() {
log.info(">>>>>>>>>>> xxl-job config init.");
XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
xxlJobSpringExecutor.setAdminAddresses(xxlJobProperties.getAdminAddresses());
xxlJobSpringExecutor.setAccessToken(xxlJobProperties.getAccessToken());
XxlJobProperties.Executor executor = xxlJobProperties.getExecutor();
xxlJobSpringExecutor.setAppname(executor.getAppname());
xxlJobSpringExecutor.setAddress(executor.getAddress());
xxlJobSpringExecutor.setIp(executor.getIp());
xxlJobSpringExecutor.setPort(executor.getPort());
xxlJobSpringExecutor.setLogPath(executor.getLogPath());
xxlJobSpringExecutor.setLogRetentionDays(executor.getLogRetentionDays());
return xxlJobSpringExecutor;
}
}
启动应用
启动成功后 查看控制台 执行器界面 成功注册到 控制中心
编写测试方法
复制官方demo
创建 SampleService.java 将官方demo复制进来
@Slf4j
@Service
public class SampleService {
@XxlJob("demoJobHandler")
public void demoJobHandler() throws Exception {
XxlJobHelper.log("XXL-JOB, Hello World.");
for (int i = 0; i < 5; i++) {
XxlJobHelper.log("beat at:" + i);
TimeUnit.SECONDS.sleep(2);
}
}
@XxlJob("shardingJobHandler")
public void shardingJobHandler() throws Exception {
int shardIndex = XxlJobHelper.getShardIndex();
int shardTotal = XxlJobHelper.getShardTotal();
XxlJobHelper.log("分片参数:当前分片序号 = {}, 总分片数 = {}", shardIndex, shardTotal);
for (int i = 0; i < shardTotal; i++) {
if (i == shardIndex) {
XxlJobHelper.log("第 {} 片, 命中分片开始处理", i);
} else {
XxlJobHelper.log("第 {} 片, 忽略", i);
}
}
}
@XxlJob("commandJobHandler")
public void commandJobHandler() throws Exception {
String command = XxlJobHelper.getJobParam();
int exitValue = -1;
BufferedReader bufferedReader = null;
try {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command(command);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
BufferedInputStream bufferedInputStream = new BufferedInputStream(process.getInputStream());
bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
XxlJobHelper.log(line);
}
process.waitFor();
exitValue = process.exitValue();
} catch (Exception e) {
XxlJobHelper.log(e);
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}
if (exitValue == 0) {
} else {
XxlJobHelper.handleFail("command exit value(" + exitValue + ") is failed");
}
}
@XxlJob("httpJobHandler")
public void httpJobHandler() throws Exception {
String param = XxlJobHelper.getJobParam();
if (param == null || param.trim().length() == 0) {
XxlJobHelper.log("param[" + param + "] invalid.");
XxlJobHelper.handleFail();
return;
}
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();
}
}
if (url == null || url.trim().length() == 0) {
XxlJobHelper.log("url[" + url + "] invalid.");
XxlJobHelper.handleFail();
return;
}
if (method == null || !Arrays.asList("GET", "POST").contains(method)) {
XxlJobHelper.log("method[" + method + "] invalid.");
XxlJobHelper.handleFail();
return;
}
boolean isPostMethod = method.equals("POST");
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
try {
URL realUrl = new URL(url);
connection = (HttpURLConnection) realUrl.openConnection();
connection.setRequestMethod(method);
connection.setDoOutput(isPostMethod);
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");
connection.connect();
if (isPostMethod && data != null && data.trim().length() > 0) {
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.write(data.getBytes("UTF-8"));
dataOutputStream.flush();
dataOutputStream.close();
}
int statusCode = connection.getResponseCode();
if (statusCode != 200) {
throw new RuntimeException("Http Request StatusCode(" + statusCode + ") Invalid.");
}
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();
XxlJobHelper.log(responseMsg);
return;
} catch (Exception e) {
XxlJobHelper.log(e);
XxlJobHelper.handleFail();
return;
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (Exception e2) {
XxlJobHelper.log(e2);
}
}
}
@XxlJob(value = "demoJobHandler2", init = "init", destroy = "destroy")
public void demoJobHandler2() throws Exception {
XxlJobHelper.log("XXL-JOB, Hello World.");
}
public void init() {
log.info("init");
}
public void destroy() {
log.info("destory");
}
}
官方demo涵盖了大部分的使用案例 大家一定要仔细阅读
执行测试
编写好代码后重启服务 日志输出所有扫描到的demo案例 进入控制台 任务管理 执行案例 查看 调度日志 任务的执行状态和具体执行返回的内容等
项目地址
项目已上传到gitee 地址: springboot-xxl-job-demo 如果帮到您了,请帮忙点个star
|