refactor(core):重构远程调用客户端实现

- 使用 HttpTool 替代自定义的 ExecutorBizClient 和 XxlJobRemotingUtil
- 统一通过 Const 类引用访问令牌常量
- 调整超时配置单位为秒并更新相关注释
- 废弃旧版 ExecutorBizClient 和 XxlJobRemotingUtil 类
- 更新测试类中的客户端构建方式以适配新的实现
- 修改 OpenAPI 控制器中访问令牌请求头获取方式
3.3.0-release
xuxueli 2 months ago
parent fa0ce058d8
commit 25bcba265e

@ -6,10 +6,11 @@ import com.xxl.job.admin.scheduler.complete.JobCompleter;
import com.xxl.job.admin.scheduler.thread.*;
import com.xxl.job.admin.scheduler.trigger.JobTrigger;
import com.xxl.job.admin.util.I18nUtil;
import com.xxl.job.core.constant.Const;
import com.xxl.job.core.openapi.ExecutorBiz;
import com.xxl.job.core.openapi.client.ExecutorBizClient;
import com.xxl.job.core.constant.ExecutorBlockStrategyEnum;
import com.xxl.tool.core.StringTool;
import com.xxl.tool.http.HttpTool;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -162,10 +163,11 @@ public class XxlJobAdminBootstrap implements InitializingBean, DisposableBean {
}
// set-cache
executorBiz = new ExecutorBizClient(address,
XxlJobAdminBootstrap.getInstance().getAccessToken(),
XxlJobAdminBootstrap.getInstance().getTimeout());
executorBiz = HttpTool.createClient()
.url(address)
.timeout(XxlJobAdminBootstrap.getInstance().getTimeout() * 1000)
.header(Const.XXL_JOB_ACCESS_TOKEN, XxlJobAdminBootstrap.getInstance().getAccessToken())
.proxy(ExecutorBiz.class);
executorBizRepository.put(address, executorBiz);
return executorBiz;
}

@ -1,10 +1,10 @@
package com.xxl.job.admin.scheduler.openapi;
import com.xxl.job.admin.scheduler.config.XxlJobAdminBootstrap;
import com.xxl.job.core.constant.Const;
import com.xxl.job.core.openapi.AdminBiz;
import com.xxl.job.core.openapi.model.HandleCallbackRequest;
import com.xxl.job.core.openapi.model.RegistryRequest;
import com.xxl.job.core.util.XxlJobRemotingUtil;
import com.xxl.sso.core.annotation.XxlSso;
import com.xxl.tool.core.StringTool;
import com.xxl.tool.gson.GsonTool;
@ -33,7 +33,7 @@ public class OpenApiController {
@XxlSso(login = false)
public Object api(HttpServletRequest request,
@PathVariable("uri") String uri,
@RequestHeader(XxlJobRemotingUtil.XXL_JOB_ACCESS_TOKEN) String accesstoken,
@RequestHeader(Const.XXL_JOB_ACCESS_TOKEN) String accesstoken,
@RequestBody(required = false) String requestBody) {
// valid

@ -54,7 +54,7 @@ spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFact
### xxl-job, access token
xxl.job.accessToken=default_token
### xxl-job, timeout
### xxl-job, timeout by second, default 3s
xxl.job.timeout=3
### xxl-job, i18n (default is zh_CN, and you can choose "zh_CN", "zh_TC" and "en")

@ -25,7 +25,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
public class AdminBizTest {
private static final Logger logger = LoggerFactory.getLogger(AdminBizTest.class);
// admin-client
private static String addressUrl = "http://127.0.0.1:8080/xxl-job-admin";
private static String accessToken = "default_token";
@ -39,7 +38,6 @@ public class AdminBizTest {
.proxy(AdminBiz.class);
}
@Test
public void callback() throws Exception {
AdminBiz adminBiz = buildClient();

@ -1,13 +1,16 @@
package com.xxl.job.executorbiz;
import com.xxl.job.core.constant.Const;
import com.xxl.job.core.openapi.ExecutorBiz;
import com.xxl.job.core.openapi.client.ExecutorBizClient;
import com.xxl.job.core.openapi.model.*;
import com.xxl.job.core.constant.ExecutorBlockStrategyEnum;
import com.xxl.job.core.glue.GlueTypeEnum;
import com.xxl.tool.http.HttpTool;
import com.xxl.tool.response.Response;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* executor api test
@ -15,15 +18,22 @@ import org.junit.jupiter.api.Test;
* Created by xuxueli on 17/5/12.
*/
public class ExecutorBizTest {
private static final Logger logger = LoggerFactory.getLogger(ExecutorBizTest.class);
// admin-client
private static String addressUrl = "http://127.0.0.1:9999/";
private static String accessToken = "default_token";
private static int timeout = 3;
private ExecutorBiz buildClient(){
return HttpTool.createClient()
.url(addressUrl)
.timeout(3 * 1000)
.header(Const.XXL_JOB_ACCESS_TOKEN, accessToken)
.proxy(ExecutorBiz.class);
}
@Test
public void beat() throws Exception {
ExecutorBiz executorBiz = new ExecutorBizClient(addressUrl, accessToken, timeout);
ExecutorBiz executorBiz = buildClient();
// Act
final Response<String> retval = executorBiz.beat();
@ -36,7 +46,7 @@ public class ExecutorBizTest {
@Test
public void idleBeat(){
ExecutorBiz executorBiz = new ExecutorBizClient(addressUrl, accessToken, timeout);
ExecutorBiz executorBiz = buildClient();
final int jobId = 0;
@ -52,7 +62,7 @@ public class ExecutorBizTest {
@Test
public void run(){
ExecutorBiz executorBiz = new ExecutorBizClient(addressUrl, accessToken, timeout);
ExecutorBiz executorBiz = buildClient();
// trigger data
final TriggerRequest triggerParam = new TriggerRequest();
@ -76,7 +86,7 @@ public class ExecutorBizTest {
@Test
public void kill(){
ExecutorBiz executorBiz = new ExecutorBizClient(addressUrl, accessToken, timeout);
ExecutorBiz executorBiz = buildClient();
final int jobId = 0;
@ -92,7 +102,7 @@ public class ExecutorBizTest {
@Test
public void log(){
ExecutorBiz executorBiz = new ExecutorBizClient(addressUrl, accessToken, timeout);
ExecutorBiz executorBiz = buildClient();
final long logDateTim = 0L;
final long logId = 0;

@ -1,61 +0,0 @@
package com.xxl.job.core.openapi.client;
import com.xxl.job.core.openapi.ExecutorBiz;
import com.xxl.job.core.openapi.model.*;
import com.xxl.job.core.util.XxlJobRemotingUtil;
import com.xxl.tool.response.Response;
/**
* admin api test
*
* @author xuxueli 2017-07-28 22:14:52
*/
public class ExecutorBizClient implements ExecutorBiz {
public ExecutorBizClient() {
}
public ExecutorBizClient(String addressUrl, String accessToken, int timeout) {
this.addressUrl = addressUrl;
this.accessToken = accessToken;
this.timeout = timeout;
// valid
if (!this.addressUrl.endsWith("/")) {
this.addressUrl = this.addressUrl + "/";
}
if (!(this.timeout >=1 && this.timeout <= 10)) {
this.timeout = 3;
}
}
private String addressUrl ;
private String accessToken;
private int timeout;
@Override
public Response<String> beat() {
return XxlJobRemotingUtil.postBody(addressUrl+"beat", accessToken, timeout, "", String.class);
}
@Override
public Response<String> idleBeat(IdleBeatRequest idleBeatRequest){
return XxlJobRemotingUtil.postBody(addressUrl+"idleBeat", accessToken, timeout, idleBeatRequest, String.class);
}
@Override
public Response<String> run(TriggerRequest triggerRequest) {
return XxlJobRemotingUtil.postBody(addressUrl + "run", accessToken, timeout, triggerRequest, String.class);
}
@Override
public Response<String> kill(KillRequest killRequest) {
return XxlJobRemotingUtil.postBody(addressUrl + "kill", accessToken, timeout, killRequest, String.class);
}
@Override
public Response<LogResult> log(LogRequest logRequest) {
return XxlJobRemotingUtil.postBody(addressUrl + "log", accessToken, timeout, logRequest, LogResult.class);
}
}

@ -1,10 +1,10 @@
package com.xxl.job.core.server;
import com.xxl.job.core.constant.Const;
import com.xxl.job.core.openapi.ExecutorBiz;
import com.xxl.job.core.openapi.impl.ExecutorBizImpl;
import com.xxl.job.core.openapi.model.*;
import com.xxl.job.core.thread.ExecutorRegistryThread;
import com.xxl.job.core.util.XxlJobRemotingUtil;
import com.xxl.tool.exception.ThrowableTool;
import com.xxl.tool.gson.GsonTool;
import com.xxl.tool.response.Response;
@ -149,7 +149,7 @@ public class EmbedServer {
String uri = msg.uri();
HttpMethod httpMethod = msg.method();
boolean keepAlive = HttpUtil.isKeepAlive(msg);
String accessTokenReq = msg.headers().get(XxlJobRemotingUtil.XXL_JOB_ACCESS_TOKEN);
String accessTokenReq = msg.headers().get(Const.XXL_JOB_ACCESS_TOKEN);
// invoke
bizThreadPool.execute(new Runnable() {

@ -1,163 +0,0 @@
package com.xxl.job.core.util;
import com.xxl.tool.gson.GsonTool;
import com.xxl.tool.response.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* @author xuxueli 2018-11-25 00:55:31
*/
public class XxlJobRemotingUtil {
private static Logger logger = LoggerFactory.getLogger(XxlJobRemotingUtil.class);
public static final String XXL_JOB_ACCESS_TOKEN = "XXL-JOB-ACCESS-TOKEN";
// trust-https start
private static void trustAllHosts(HttpsURLConnection connection) {
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
SSLSocketFactory newFactory = sc.getSocketFactory();
connection.setSSLSocketFactory(newFactory);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
connection.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
}
private static final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}};
// trust-https end
/**
* post
*
* @param url
* @param accessToken
* @param timeout by second
* @param requestObj
* @param returnTargClassOfT
* @return
*/
public static Response postBody(String url, String accessToken, int timeout, Object requestObj, Class returnTargClassOfT) {
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
DataOutputStream dataOutputStream = null;
try {
// connection
URL realUrl = new URL(url);
connection = (HttpURLConnection) realUrl.openConnection();
// trust-https
boolean useHttps = url.startsWith("https");
if (useHttps) {
HttpsURLConnection https = (HttpsURLConnection) connection;
trustAllHosts(https);
}
// connection setting
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setReadTimeout(timeout * 1000);
connection.setConnectTimeout(timeout * 1000);
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.setRequestProperty("Accept-Charset", "application/json;charset=UTF-8");
if(accessToken!=null && !accessToken.trim().isEmpty()){
connection.setRequestProperty(XXL_JOB_ACCESS_TOKEN, accessToken);
}
// do connection
connection.connect();
// write requestBody
if (requestObj != null) {
String requestBody = GsonTool.toJson(requestObj);
dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.write(requestBody.getBytes("UTF-8"));
dataOutputStream.flush();
dataOutputStream.close();
}
/*byte[] requestBodyBytes = requestBody.getBytes("UTF-8");
connection.setRequestProperty("Content-Length", String.valueOf(requestBodyBytes.length));
OutputStream outwritestream = connection.getOutputStream();
outwritestream.write(requestBodyBytes);
outwritestream.flush();
outwritestream.close();*/
// valid StatusCode
int statusCode = connection.getResponseCode();
if (statusCode != 200) {
return Response.ofFail("xxl-job remoting fail, StatusCode("+ statusCode +") invalid. for url : " + url);
}
// 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 resultJson = result.toString();
// parse returnT
try {
Response returnT = GsonTool.fromJson(resultJson, Response.class, returnTargClassOfT);
return returnT;
} catch (Exception e) {
logger.error("xxl-job remoting (url="+url+") response content invalid("+ resultJson +").", e);
return Response.ofFail("xxl-job remoting (url="+url+") response content invalid("+ resultJson +").");
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
return Response.ofFail("xxl-job remoting error("+ e.getMessage() +"), for url : " + url);
} finally {
try {
if (dataOutputStream != null) {
dataOutputStream.close();
}
if (bufferedReader != null) {
bufferedReader.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (Exception e2) {
logger.error(e2.getMessage(), e2);
}
}
}
}

@ -0,0 +1,61 @@
//package com.xxl.job.core.openapi.client;
//
//import com.xxl.job.core.openapi.ExecutorBiz;
//import com.xxl.job.core.openapi.model.*;
//import com.xxl.job.core.util.XxlJobRemotingUtil;
//import com.xxl.tool.response.Response;
//
///**
// * admin api test
// *
// * @author xuxueli 2017-07-28 22:14:52
// */
//public class ExecutorBizClient implements ExecutorBiz {
//
// public ExecutorBizClient() {
// }
// public ExecutorBizClient(String addressUrl, String accessToken, int timeout) {
// this.addressUrl = addressUrl;
// this.accessToken = accessToken;
// this.timeout = timeout;
//
// // valid
// if (!this.addressUrl.endsWith("/")) {
// this.addressUrl = this.addressUrl + "/";
// }
// if (!(this.timeout >=1 && this.timeout <= 10)) {
// this.timeout = 3;
// }
// }
//
// private String addressUrl ;
// private String accessToken;
// private int timeout;
//
//
// @Override
// public Response<String> beat() {
// return XxlJobRemotingUtil.postBody(addressUrl+"beat", accessToken, timeout, "", String.class);
// }
//
// @Override
// public Response<String> idleBeat(IdleBeatRequest idleBeatRequest){
// return XxlJobRemotingUtil.postBody(addressUrl+"idleBeat", accessToken, timeout, idleBeatRequest, String.class);
// }
//
// @Override
// public Response<String> run(TriggerRequest triggerRequest) {
// return XxlJobRemotingUtil.postBody(addressUrl + "run", accessToken, timeout, triggerRequest, String.class);
// }
//
// @Override
// public Response<String> kill(KillRequest killRequest) {
// return XxlJobRemotingUtil.postBody(addressUrl + "kill", accessToken, timeout, killRequest, String.class);
// }
//
// @Override
// public Response<LogResult> log(LogRequest logRequest) {
// return XxlJobRemotingUtil.postBody(addressUrl + "log", accessToken, timeout, logRequest, LogResult.class);
// }
//
//}

@ -0,0 +1,163 @@
//package com.xxl.job.core.util;
//
//import com.xxl.tool.gson.GsonTool;
//import com.xxl.tool.response.Response;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import javax.net.ssl.*;
//import java.io.BufferedReader;
//import java.io.DataOutputStream;
//import java.io.InputStreamReader;
//import java.net.HttpURLConnection;
//import java.net.URL;
//import java.security.cert.CertificateException;
//import java.security.cert.X509Certificate;
//
///**
// * @author xuxueli 2018-11-25 00:55:31
// */
//public class XxlJobRemotingUtil {
// private static Logger logger = LoggerFactory.getLogger(XxlJobRemotingUtil.class);
// public static final String XXL_JOB_ACCESS_TOKEN = "XXL-JOB-ACCESS-TOKEN";
//
//
// // trust-https start
// private static void trustAllHosts(HttpsURLConnection connection) {
// try {
// SSLContext sc = SSLContext.getInstance("TLS");
// sc.init(null, trustAllCerts, new java.security.SecureRandom());
// SSLSocketFactory newFactory = sc.getSocketFactory();
//
// connection.setSSLSocketFactory(newFactory);
// } catch (Exception e) {
// logger.error(e.getMessage(), e);
// }
// connection.setHostnameVerifier(new HostnameVerifier() {
// @Override
// public boolean verify(String hostname, SSLSession session) {
// return true;
// }
// });
// }
// private static final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
// @Override
// public java.security.cert.X509Certificate[] getAcceptedIssuers() {
// return new java.security.cert.X509Certificate[]{};
// }
// @Override
// public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// }
// @Override
// public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// }
// }};
// // trust-https end
//
//
// /**
// * post
// *
// * @param url
// * @param accessToken
// * @param timeout by second
// * @param requestObj
// * @param returnTargClassOfT
// * @return
// */
// public static Response postBody(String url, String accessToken, int timeout, Object requestObj, Class returnTargClassOfT) {
// HttpURLConnection connection = null;
// BufferedReader bufferedReader = null;
// DataOutputStream dataOutputStream = null;
// try {
// // connection
// URL realUrl = new URL(url);
// connection = (HttpURLConnection) realUrl.openConnection();
//
// // trust-https
// boolean useHttps = url.startsWith("https");
// if (useHttps) {
// HttpsURLConnection https = (HttpsURLConnection) connection;
// trustAllHosts(https);
// }
//
// // connection setting
// connection.setRequestMethod("POST");
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setUseCaches(false);
// connection.setReadTimeout(timeout * 1000);
// connection.setConnectTimeout(timeout * 1000);
// connection.setRequestProperty("connection", "Keep-Alive");
// connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
// connection.setRequestProperty("Accept-Charset", "application/json;charset=UTF-8");
//
// if(accessToken!=null && !accessToken.trim().isEmpty()){
// connection.setRequestProperty(XXL_JOB_ACCESS_TOKEN, accessToken);
// }
//
// // do connection
// connection.connect();
//
// // write requestBody
// if (requestObj != null) {
// String requestBody = GsonTool.toJson(requestObj);
//
// dataOutputStream = new DataOutputStream(connection.getOutputStream());
// dataOutputStream.write(requestBody.getBytes("UTF-8"));
// dataOutputStream.flush();
// dataOutputStream.close();
// }
//
// /*byte[] requestBodyBytes = requestBody.getBytes("UTF-8");
// connection.setRequestProperty("Content-Length", String.valueOf(requestBodyBytes.length));
// OutputStream outwritestream = connection.getOutputStream();
// outwritestream.write(requestBodyBytes);
// outwritestream.flush();
// outwritestream.close();*/
//
// // valid StatusCode
// int statusCode = connection.getResponseCode();
// if (statusCode != 200) {
// return Response.ofFail("xxl-job remoting fail, StatusCode("+ statusCode +") invalid. for url : " + url);
// }
//
// // 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 resultJson = result.toString();
//
// // parse returnT
// try {
// Response returnT = GsonTool.fromJson(resultJson, Response.class, returnTargClassOfT);
// return returnT;
// } catch (Exception e) {
// logger.error("xxl-job remoting (url="+url+") response content invalid("+ resultJson +").", e);
// return Response.ofFail("xxl-job remoting (url="+url+") response content invalid("+ resultJson +").");
// }
//
// } catch (Exception e) {
// logger.error(e.getMessage(), e);
// return Response.ofFail("xxl-job remoting error("+ e.getMessage() +"), for url : " + url);
// } finally {
// try {
// if (dataOutputStream != null) {
// dataOutputStream.close();
// }
// if (bufferedReader != null) {
// bufferedReader.close();
// }
// if (connection != null) {
// connection.disconnect();
// }
// } catch (Exception e2) {
// logger.error(e2.getMessage(), e2);
// }
// }
// }
//
//}
Loading…
Cancel
Save