官網(wǎng)下載最新版本的xxl-job
idea打開項(xiàng)目:
1.新建數(shù)據(jù)庫
根據(jù)項(xiàng)目中的數(shù)據(jù)庫腳本建好數(shù)據(jù)庫
1.打開配置中心xxl-job-admin的配置文件application.properties
配置好jdbc和email垛叨,啟動(dòng)xxl-job-admin項(xiàng)目
### 調(diào)度中心JDBC鏈接:鏈接地址請保持和 2.1章節(jié) 所創(chuàng)建的調(diào)度數(shù)據(jù)庫的地址一致
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/xxl_job?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root_pwd
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
### 報(bào)警郵箱
spring.mail.host=smtp.qq.com
spring.mail.port=25
spring.mail.username=xxx@qq.com
spring.mail.password=xxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
### 調(diào)度中心通訊TOKEN [選填]:非空時(shí)啟用鲁沥;
xxl.job.accessToken=
### 調(diào)度中心國際化配置 [必填]: 默認(rèn)為 "zh_CN"/中文簡體, 可選范圍為 "zh_CN"/中文簡體, "zh_TC"/中文繁體 and "en"/英文羞反;
xxl.job.i18n=zh_CN
## 調(diào)度線程池最大線程配置【必填】
xxl.job.triggerpool.fast.max=200
xxl.job.triggerpool.slow.max=100
### 調(diào)度中心日志表數(shù)據(jù)保存天數(shù) [必填]:過期日志自動(dòng)清理弧满;限制大于等于7時(shí)生效调鬓,否則, 如-1褐筛,關(guān)閉自動(dòng)清理功能互广;
xxl.job.logretentiondays=30
2.部署項(xiàng)目
如果已經(jīng)正確進(jìn)行上述配置倦青,可將項(xiàng)目編譯打包部署。
調(diào)度中心訪問地址:http://localhost:8080/xxl-job-admin (該地址執(zhí)行器將會(huì)使用到芜茵,作為回調(diào)地址)
默認(rèn)登錄賬號(hào) “admin/123456”, 登錄后運(yùn)行界面如下圖所示:
3.創(chuàng)建并運(yùn)行執(zhí)行器
項(xiàng)目自帶兩個(gè)版本的執(zhí)行器叙量,以springboot版本為例:
啟動(dòng)執(zhí)行器:
如果報(bào)異常:Address already in use: bind,則修改一下端口號(hào)xxl.job.executor.port即可:
執(zhí)行器列舉了五種執(zhí)行任務(wù)的方式:
package com.xxl.job.executor.service.jobhandler;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
/**
* XxlJob開發(fā)示例(Bean模式)
*
* 開發(fā)步驟:
* 1九串、任務(wù)開發(fā):在Spring Bean實(shí)例中绞佩,開發(fā)Job方法;
* 2猪钮、注解配置:為Job方法添加注解 "@XxlJob(value="自定義jobhandler名稱", init = "JobHandler初始化方法", destroy = "JobHandler銷毀方法")"品山,注解value值對應(yīng)的是調(diào)度中心新建任務(wù)的JobHandler屬性的值。
* 3躬贡、執(zhí)行日志:需要通過 "XxlJobHelper.log" 打印執(zhí)行日志谆奥;
* 4、任務(wù)結(jié)果:默認(rèn)任務(wù)結(jié)果為 "成功" 狀態(tài)拂玻,不需要主動(dòng)設(shè)置酸些;如有訴求,比如設(shè)置任務(wù)結(jié)果為失敗檐蚜,可以通過 "XxlJobHelper.handleFail/handleSuccess" 自主設(shè)置任務(wù)結(jié)果魄懂;
*
* @author xuxueli 2019-12-11 21:52:51
*/
@Component
public class SampleXxlJob {
private static Logger logger = LoggerFactory.getLogger(SampleXxlJob.class);
/**
* 1、簡單任務(wù)示例(Bean模式)
*/
@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);
}
// default success
}
/**
* 2闯第、分片廣播任務(wù)
*/
@XxlJob("shardingJobHandler")
public void shardingJobHandler() throws Exception {
// 分片參數(shù)
int shardIndex = XxlJobHelper.getShardIndex();
int shardTotal = XxlJobHelper.getShardTotal();
XxlJobHelper.log("分片參數(shù):當(dāng)前分片序號(hào) = {}, 總分片數(shù) = {}", shardIndex, shardTotal);
// 業(yè)務(wù)邏輯
for (int i = 0; i < shardTotal; i++) {
if (i == shardIndex) {
XxlJobHelper.log("第 {} 片, 命中分片開始處理", i);
} else {
XxlJobHelper.log("第 {} 片, 忽略", i);
}
}
}
/**
* 3市栗、命令行任務(wù)
*/
@XxlJob("commandJobHandler")
public void commandJobHandler() throws Exception {
String command = XxlJobHelper.getJobParam();
int exitValue = -1;
BufferedReader bufferedReader = null;
try {
// command process
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command(command);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
//Process process = Runtime.getRuntime().exec(command);
BufferedInputStream bufferedInputStream = new BufferedInputStream(process.getInputStream());
bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));
// command log
String line;
while ((line = bufferedReader.readLine()) != null) {
XxlJobHelper.log(line);
}
// command exit
process.waitFor();
exitValue = process.exitValue();
} catch (Exception e) {
XxlJobHelper.log(e);
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}
if (exitValue == 0) {
// default success
} else {
XxlJobHelper.handleFail("command exit value("+exitValue+") is failed");
}
}
/**
* 4、跨平臺(tái)Http任務(wù)
* 參數(shù)示例:
* "url: http://www.baidu.com\n" +
* "method: get\n" +
* "data: content\n";
*/
@XxlJob("httpJobHandler")
public void httpJobHandler() throws Exception {
// param parse
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();
}
}
// param valid
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");
// request
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
try {
// connection
URL realUrl = new URL(url);
connection = (HttpURLConnection) realUrl.openConnection();
// connection setting
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");
// do connection
connection.connect();
// data
if (isPostMethod && data!=null && data.trim().length()>0) {
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.write(data.getBytes("UTF-8"));
dataOutputStream.flush();
dataOutputStream.close();
}
// valid StatusCode
int statusCode = connection.getResponseCode();
if (statusCode != 200) {
throw new RuntimeException("Http Request StatusCode(" + statusCode + ") Invalid.");
}
// result
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);
}
}
}
/**
* 5咳短、生命周期任務(wù)示例:任務(wù)初始化與銷毀時(shí)填帽,支持自定義相關(guān)邏輯;
*/
@XxlJob(value = "demoJobHandler2", init = "init", destroy = "destroy")
public void demoJobHandler2() throws Exception {
XxlJobHelper.log("XXL-JOB, Hello World.");
}
public void init(){
logger.info("init");
}
public void destroy(){
logger.info("destory");
}
}
4.以“簡單任務(wù)示例(Bean模式)”為例咙好,在頁面添加任務(wù):
JobHandler與項(xiàng)目中注解@XxlJob("demoJobHandler")中的名稱一致:
執(zhí)行該任務(wù):
可在“調(diào)度日志”中查看到執(zhí)行記錄:
也能查看具體的日志內(nèi)容:
可在“執(zhí)行器管理”中添加不同類型分執(zhí)行器: