xxl-job 2.3.0增加RestJob JobHandler,调度执行更加友好一点
在xxl-job-executor模块的com.xxl.job.executor.service.jobhandler下增加RestXxlJob.java
package com.xxl.job.executor.service.jobhandler;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
@Component
public class RestXxlJob {
private static Logger logger = LoggerFactory.getLogger(RestXxlJob.class);
/**
* 跨平台Http Rest任务
* 参数示例:
* "url: http://www.baidu.com\n" +
* "method: get\n" +
* "data: content\n";
*/
@XxlJob("RestJob")
public void RestXxlJob() 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");
CloseableHttpClient httpclient = null;
HttpResponse response = null;
try {
httpclient = HttpClients.createDefault();
//httpClient 4.5版本的超时参数配置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5_000).setConnectionRequestTimeout(30_000)
.setSocketTimeout(30_000).build();
//往BODY里填充数据主体
StringEntity entitys=new StringEntity(data, "utf-8");
entitys.setContentEncoding("UTF-8");
entitys.setContentType("application/xml");
if( isPostMethod ){
HttpPost post=new HttpPost(url);
post.setConfig(requestConfig);
post.setEntity(entitys);
response = httpclient.execute(post);
}else {
HttpGet httpGet = new HttpGet(url);
response = httpclient.execute(httpGet);
}
// valid StatusCode
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
throw new RuntimeException("Http Request StatusCode(" + statusCode + ") Invalid.");
}
XxlJobHelper.log(EntityUtils.toString(response.getEntity(),"UTF-8"));
return;
} catch (Exception e) {
XxlJobHelper.log(e);
XxlJobHelper.handleFail();
return;
} finally {
try {
if (httpclient != null) {
httpclient.close();
}
} catch (Exception e2) {
XxlJobHelper.log(e2);
}
}
}
public void init(){
logger.info("init");
}
public void destroy(){
logger.info("destory");
}
}
任务调用参考下图
url:http://xx:xxx/abc/doJob?P=abc
method:post
data:
url支持待参数,用?分隔
method支持post和get
Ruoyi框架对Api响应进行了封装,可以考虑进行二次解析,参考代码如下
@XxlJob("httpJobRuoYiHandler")
public void httpJobRuoYiHandler() 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(30 * 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();
JSONObject jsonObject = JSONObject.parseObject(responseMsg);
if ( jsonObject != null && (jsonObject.getString("code")==null ||
!(jsonObject.getString("code").equals("200") || jsonObject.getString("code").equals("0"))))
{
throw new RuntimeException("Http Request(Ruoyi AjaxResult) StatusCode(" + jsonObject.getString("code") + ") Invalid.,Msg("+jsonObject.getString("msg")+")");
}
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);
}
}
}
调用JobHandler使用httpJobRuoYiHandler,示例如下: