- 3.1、"ShardingUtil" 组件废弃:改用 "XxlJobHelper.getShardIndex()/getShardTotal();" 获取分片参数; - 3.2、"XxlJobLogger" 组件废弃:改用 "XxlJobHelper.log" 进行日志输出; - 4、【优化】任务核心类 "IJobHandler" 的 "execute" 方法取消出入参设计。改为通过 "XxlJobHelper.getJobParam" 获取任务参数并替代方法入参,通过 "XxlJobHelper.handleSuccess/handleFail" 设置任务结果并替代方法出参;pull/22/MERGE
parent
6339f528c5
commit
5dfc6a1092
@ -0,0 +1,255 @@
|
||||
package com.xxl.job.core.context;
|
||||
|
||||
import com.xxl.job.core.log.XxlJobFileAppender;
|
||||
import com.xxl.job.core.util.DateUtil;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.slf4j.helpers.FormattingTuple;
|
||||
import org.slf4j.helpers.MessageFormatter;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* helper for xxl-job
|
||||
*
|
||||
* @author xuxueli 2020-11-05
|
||||
*/
|
||||
public class XxlJobHelper {
|
||||
|
||||
// ---------------------- base info ----------------------
|
||||
|
||||
/**
|
||||
* current JobId
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static long getJobId() {
|
||||
XxlJobContext xxlJobContext = XxlJobContext.getXxlJobContext();
|
||||
if (xxlJobContext == null) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return xxlJobContext.getJobId();
|
||||
}
|
||||
|
||||
/**
|
||||
* current JobParam
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static String getJobParam() {
|
||||
XxlJobContext xxlJobContext = XxlJobContext.getXxlJobContext();
|
||||
if (xxlJobContext == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return xxlJobContext.getJobParam();
|
||||
}
|
||||
|
||||
// ---------------------- for log ----------------------
|
||||
|
||||
/**
|
||||
* current JobLogFileName
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static String getJobLogFileName() {
|
||||
XxlJobContext xxlJobContext = XxlJobContext.getXxlJobContext();
|
||||
if (xxlJobContext == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return xxlJobContext.getJobLogFileName();
|
||||
}
|
||||
|
||||
// ---------------------- for shard ----------------------
|
||||
|
||||
/**
|
||||
* current ShardIndex
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static int getShardIndex() {
|
||||
XxlJobContext xxlJobContext = XxlJobContext.getXxlJobContext();
|
||||
if (xxlJobContext == null) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return xxlJobContext.getShardIndex();
|
||||
}
|
||||
|
||||
/**
|
||||
* current ShardTotal
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static int getShardTotal() {
|
||||
XxlJobContext xxlJobContext = XxlJobContext.getXxlJobContext();
|
||||
if (xxlJobContext == null) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return xxlJobContext.getShardTotal();
|
||||
}
|
||||
|
||||
// ---------------------- tool for log ----------------------
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger("xxl-job logger");
|
||||
|
||||
/**
|
||||
* append log with pattern
|
||||
*
|
||||
* @param appendLogPattern like "aaa {} bbb {} ccc"
|
||||
* @param appendLogArguments like "111, true"
|
||||
*/
|
||||
public static boolean log(String appendLogPattern, Object ... appendLogArguments) {
|
||||
|
||||
FormattingTuple ft = MessageFormatter.arrayFormat(appendLogPattern, appendLogArguments);
|
||||
String appendLog = ft.getMessage();
|
||||
|
||||
/*appendLog = appendLogPattern;
|
||||
if (appendLogArguments!=null && appendLogArguments.length>0) {
|
||||
appendLog = MessageFormat.format(appendLogPattern, appendLogArguments);
|
||||
}*/
|
||||
|
||||
StackTraceElement callInfo = new Throwable().getStackTrace()[1];
|
||||
return logDetail(callInfo, appendLog);
|
||||
}
|
||||
|
||||
/**
|
||||
* append exception stack
|
||||
*
|
||||
* @param e
|
||||
*/
|
||||
public static boolean log(Throwable e) {
|
||||
|
||||
StringWriter stringWriter = new StringWriter();
|
||||
e.printStackTrace(new PrintWriter(stringWriter));
|
||||
String appendLog = stringWriter.toString();
|
||||
|
||||
StackTraceElement callInfo = new Throwable().getStackTrace()[1];
|
||||
return logDetail(callInfo, appendLog);
|
||||
}
|
||||
|
||||
/**
|
||||
* append log
|
||||
*
|
||||
* @param callInfo
|
||||
* @param appendLog
|
||||
*/
|
||||
private static boolean logDetail(StackTraceElement callInfo, String appendLog) {
|
||||
XxlJobContext xxlJobContext = XxlJobContext.getXxlJobContext();
|
||||
if (xxlJobContext == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/*// "yyyy-MM-dd HH:mm:ss [ClassName]-[MethodName]-[LineNumber]-[ThreadName] log";
|
||||
StackTraceElement[] stackTraceElements = new Throwable().getStackTrace();
|
||||
StackTraceElement callInfo = stackTraceElements[1];*/
|
||||
|
||||
StringBuffer stringBuffer = new StringBuffer();
|
||||
stringBuffer.append(DateUtil.formatDateTime(new Date())).append(" ")
|
||||
.append("["+ callInfo.getClassName() + "#" + callInfo.getMethodName() +"]").append("-")
|
||||
.append("["+ callInfo.getLineNumber() +"]").append("-")
|
||||
.append("["+ Thread.currentThread().getName() +"]").append(" ")
|
||||
.append(appendLog!=null?appendLog:"");
|
||||
String formatAppendLog = stringBuffer.toString();
|
||||
|
||||
// appendlog
|
||||
String logFileName = xxlJobContext.getJobLogFileName();
|
||||
|
||||
if (logFileName!=null && logFileName.trim().length()>0) {
|
||||
XxlJobFileAppender.appendLog(logFileName, formatAppendLog);
|
||||
return true;
|
||||
} else {
|
||||
logger.info(">>>>>>>>>>> {}", formatAppendLog);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------- tool for handleResult ----------------------
|
||||
|
||||
/**
|
||||
* handle success
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static boolean handleSuccess(){
|
||||
return handleResult(XxlJobContext.HANDLE_COCE_SUCCESS, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* handle success with log msg
|
||||
*
|
||||
* @param handleMsg
|
||||
* @return
|
||||
*/
|
||||
public static boolean handleSuccess(String handleMsg) {
|
||||
return handleResult(XxlJobContext.HANDLE_COCE_SUCCESS, handleMsg);
|
||||
}
|
||||
|
||||
/**
|
||||
* handle fail
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static boolean handleFail(){
|
||||
return handleResult(XxlJobContext.HANDLE_COCE_FAIL, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* handle fail with log msg
|
||||
*
|
||||
* @param handleMsg
|
||||
* @return
|
||||
*/
|
||||
public static boolean handleFail(String handleMsg) {
|
||||
return handleResult(XxlJobContext.HANDLE_COCE_FAIL, handleMsg);
|
||||
}
|
||||
|
||||
/**
|
||||
* handle timeout
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static boolean handleTimeout(){
|
||||
return handleResult(XxlJobContext.HANDLE_COCE_TIMEOUT, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* handle timeout with log msg
|
||||
*
|
||||
* @param handleMsg
|
||||
* @return
|
||||
*/
|
||||
public static boolean handleTimeout(String handleMsg){
|
||||
return handleResult(XxlJobContext.HANDLE_COCE_TIMEOUT, handleMsg);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param handleCode
|
||||
*
|
||||
* 200 : success
|
||||
* 500 : fail
|
||||
* 502 : timeout
|
||||
*
|
||||
* @param handleMsg
|
||||
* @return
|
||||
*/
|
||||
public static boolean handleResult(int handleCode, String handleMsg) {
|
||||
XxlJobContext xxlJobContext = XxlJobContext.getXxlJobContext();
|
||||
if (xxlJobContext == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
xxlJobContext.setHandleCode(handleCode);
|
||||
if (handleMsg != null) {
|
||||
xxlJobContext.setHandleMsg(handleMsg);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,122 @@
|
||||
package com.xxl.job.core.executor.impl;
|
||||
|
||||
import com.xxl.job.core.executor.XxlJobExecutor;
|
||||
import com.xxl.job.core.handler.annotation.XxlJob;
|
||||
import com.xxl.job.core.handler.impl.MethodJobHandler;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
/**
|
||||
* xxl-job executor (for frameless)
|
||||
*
|
||||
* @author xuxueli 2020-11-05
|
||||
*/
|
||||
public class XxlJobSimpleExecutor extends XxlJobExecutor {
|
||||
private static final Logger logger = LoggerFactory.getLogger(XxlJobSimpleExecutor.class);
|
||||
|
||||
|
||||
private List<Object> xxlJobBeanList = new ArrayList<>();
|
||||
public List<Object> getXxlJobBeanList() {
|
||||
return xxlJobBeanList;
|
||||
}
|
||||
public void setXxlJobBeanList(List<Object> xxlJobBeanList) {
|
||||
this.xxlJobBeanList = xxlJobBeanList;
|
||||
}
|
||||
|
||||
|
||||
public void start() {
|
||||
|
||||
// init JobHandler Repository (for method)
|
||||
initJobHandlerMethodRepository(xxlJobBeanList);
|
||||
|
||||
// super start
|
||||
try {
|
||||
super.start();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
super.destroy();
|
||||
}
|
||||
|
||||
|
||||
private void initJobHandlerMethodRepository(List<Object> xxlJobBeanList) {
|
||||
if (xxlJobBeanList==null || xxlJobBeanList.size()==0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// init job handler from method
|
||||
for (Object bean: xxlJobBeanList) {
|
||||
// method
|
||||
Method[] methods = bean.getClass().getDeclaredMethods();
|
||||
if (methods==null || methods.length==0) {
|
||||
continue;
|
||||
}
|
||||
for (Method executeMethod : methods) {
|
||||
|
||||
// anno
|
||||
XxlJob xxlJob = executeMethod.getAnnotation(XxlJob.class);
|
||||
if (xxlJob == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String name = xxlJob.value();
|
||||
if (name.trim().length() == 0) {
|
||||
throw new RuntimeException("xxl-job method-jobhandler name invalid, for[" + bean.getClass() + "#" + executeMethod.getName() + "] .");
|
||||
}
|
||||
if (loadJobHandler(name) != null) {
|
||||
throw new RuntimeException("xxl-job jobhandler[" + name + "] naming conflicts.");
|
||||
}
|
||||
|
||||
// execute method
|
||||
/*if (!(method.getParameterTypes().length == 1 && method.getParameterTypes()[0].isAssignableFrom(String.class))) {
|
||||
throw new RuntimeException("xxl-job method-jobhandler param-classtype invalid, for[" + bean.getClass() + "#" + method.getName() + "] , " +
|
||||
"The correct method format like \" public ReturnT<String> execute(String param) \" .");
|
||||
}
|
||||
if (!method.getReturnType().isAssignableFrom(ReturnT.class)) {
|
||||
throw new RuntimeException("xxl-job method-jobhandler return-classtype invalid, for[" + bean.getClass() + "#" + method.getName() + "] , " +
|
||||
"The correct method format like \" public ReturnT<String> execute(String param) \" .");
|
||||
}*/
|
||||
|
||||
executeMethod.setAccessible(true);
|
||||
|
||||
// init and destory
|
||||
Method initMethod = null;
|
||||
Method destroyMethod = null;
|
||||
|
||||
if (xxlJob.init().trim().length() > 0) {
|
||||
try {
|
||||
initMethod = bean.getClass().getDeclaredMethod(xxlJob.init());
|
||||
initMethod.setAccessible(true);
|
||||
} catch (NoSuchMethodException e) {
|
||||
throw new RuntimeException("xxl-job method-jobhandler initMethod invalid, for[" + bean.getClass() + "#" + executeMethod.getName() + "] .");
|
||||
}
|
||||
}
|
||||
if (xxlJob.destroy().trim().length() > 0) {
|
||||
try {
|
||||
destroyMethod = bean.getClass().getDeclaredMethod(xxlJob.destroy());
|
||||
destroyMethod.setAccessible(true);
|
||||
} catch (NoSuchMethodException e) {
|
||||
throw new RuntimeException("xxl-job method-jobhandler destroyMethod invalid, for[" + bean.getClass() + "#" + executeMethod.getName() + "] .");
|
||||
}
|
||||
}
|
||||
|
||||
// registry jobhandler
|
||||
registJobHandler(name, new MethodJobHandler(bean, executeMethod, initMethod, destroyMethod));
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -1,86 +0,0 @@
|
||||
package com.xxl.job.core.log;
|
||||
|
||||
import com.xxl.job.core.context.XxlJobContext;
|
||||
import com.xxl.job.core.util.DateUtil;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.slf4j.helpers.FormattingTuple;
|
||||
import org.slf4j.helpers.MessageFormatter;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Created by xuxueli on 17/4/28.
|
||||
*/
|
||||
public class XxlJobLogger {
|
||||
private static Logger logger = LoggerFactory.getLogger("xxl-job logger");
|
||||
|
||||
/**
|
||||
* append log
|
||||
*
|
||||
* @param callInfo
|
||||
* @param appendLog
|
||||
*/
|
||||
private static void logDetail(StackTraceElement callInfo, String appendLog) {
|
||||
|
||||
|
||||
/*// "yyyy-MM-dd HH:mm:ss [ClassName]-[MethodName]-[LineNumber]-[ThreadName] log";
|
||||
StackTraceElement[] stackTraceElements = new Throwable().getStackTrace();
|
||||
StackTraceElement callInfo = stackTraceElements[1];*/
|
||||
|
||||
StringBuffer stringBuffer = new StringBuffer();
|
||||
stringBuffer.append(DateUtil.formatDateTime(new Date())).append(" ")
|
||||
.append("["+ callInfo.getClassName() + "#" + callInfo.getMethodName() +"]").append("-")
|
||||
.append("["+ callInfo.getLineNumber() +"]").append("-")
|
||||
.append("["+ Thread.currentThread().getName() +"]").append(" ")
|
||||
.append(appendLog!=null?appendLog:"");
|
||||
String formatAppendLog = stringBuffer.toString();
|
||||
|
||||
// appendlog
|
||||
String logFileName = XxlJobContext.getXxlJobContext().getJobLogFileName();
|
||||
|
||||
if (logFileName!=null && logFileName.trim().length()>0) {
|
||||
XxlJobFileAppender.appendLog(logFileName, formatAppendLog);
|
||||
} else {
|
||||
logger.info(">>>>>>>>>>> {}", formatAppendLog);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* append log with pattern
|
||||
*
|
||||
* @param appendLogPattern like "aaa {} bbb {} ccc"
|
||||
* @param appendLogArguments like "111, true"
|
||||
*/
|
||||
public static void log(String appendLogPattern, Object ... appendLogArguments) {
|
||||
|
||||
FormattingTuple ft = MessageFormatter.arrayFormat(appendLogPattern, appendLogArguments);
|
||||
String appendLog = ft.getMessage();
|
||||
|
||||
/*appendLog = appendLogPattern;
|
||||
if (appendLogArguments!=null && appendLogArguments.length>0) {
|
||||
appendLog = MessageFormat.format(appendLogPattern, appendLogArguments);
|
||||
}*/
|
||||
|
||||
StackTraceElement callInfo = new Throwable().getStackTrace()[1];
|
||||
logDetail(callInfo, appendLog);
|
||||
}
|
||||
|
||||
/**
|
||||
* append exception stack
|
||||
*
|
||||
* @param e
|
||||
*/
|
||||
public static void log(Throwable e) {
|
||||
|
||||
StringWriter stringWriter = new StringWriter();
|
||||
e.printStackTrace(new PrintWriter(stringWriter));
|
||||
String appendLog = stringWriter.toString();
|
||||
|
||||
StackTraceElement callInfo = new Throwable().getStackTrace()[1];
|
||||
logDetail(callInfo, appendLog);
|
||||
}
|
||||
|
||||
}
|
@ -1,54 +0,0 @@
|
||||
package com.xuxueli.executor.sample.frameless.jobhandler;
|
||||
|
||||
import com.xxl.job.core.biz.model.ReturnT;
|
||||
import com.xxl.job.core.handler.IJobHandler;
|
||||
import com.xxl.job.core.log.XxlJobLogger;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
/**
|
||||
* 命令行任务
|
||||
*
|
||||
* @author xuxueli 2018-09-16 03:48:34
|
||||
*/
|
||||
public class CommandJobHandler extends IJobHandler {
|
||||
|
||||
@Override
|
||||
public ReturnT<String> execute(String param) throws Exception {
|
||||
String command = param;
|
||||
int exitValue = -1;
|
||||
|
||||
BufferedReader bufferedReader = null;
|
||||
try {
|
||||
// command process
|
||||
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) {
|
||||
XxlJobLogger.log(line);
|
||||
}
|
||||
|
||||
// command exit
|
||||
process.waitFor();
|
||||
exitValue = process.exitValue();
|
||||
} catch (Exception e) {
|
||||
XxlJobLogger.log(e);
|
||||
} finally {
|
||||
if (bufferedReader != null) {
|
||||
bufferedReader.close();
|
||||
}
|
||||
}
|
||||
|
||||
if (exitValue == 0) {
|
||||
return IJobHandler.SUCCESS;
|
||||
} else {
|
||||
return new ReturnT<String>(IJobHandler.FAIL.getCode(), "command exit value("+exitValue+") is failed");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,121 +0,0 @@
|
||||
package com.xuxueli.executor.sample.frameless.jobhandler;
|
||||
|
||||
import com.xxl.job.core.biz.model.ReturnT;
|
||||
import com.xxl.job.core.handler.IJobHandler;
|
||||
import com.xxl.job.core.log.XxlJobLogger;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* 跨平台Http任务
|
||||
*
|
||||
* @author xuxueli 2018-09-16 03:48:34
|
||||
*/
|
||||
public class HttpJobHandler extends IJobHandler {
|
||||
|
||||
@Override
|
||||
public ReturnT<String> execute(String param) throws Exception {
|
||||
|
||||
// param parse
|
||||
if (param==null || param.trim().length()==0) {
|
||||
XxlJobLogger.log("param["+ param +"] invalid.");
|
||||
return ReturnT.FAIL;
|
||||
}
|
||||
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) {
|
||||
XxlJobLogger.log("url["+ url +"] invalid.");
|
||||
return ReturnT.FAIL;
|
||||
}
|
||||
if (method==null || !Arrays.asList("GET", "POST").contains(method)) {
|
||||
XxlJobLogger.log("method["+ method +"] invalid.");
|
||||
return ReturnT.FAIL;
|
||||
}
|
||||
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();
|
||||
|
||||
XxlJobLogger.log(responseMsg);
|
||||
return ReturnT.SUCCESS;
|
||||
} catch (Exception e) {
|
||||
XxlJobLogger.log(e);
|
||||
return ReturnT.FAIL;
|
||||
} finally {
|
||||
try {
|
||||
if (bufferedReader != null) {
|
||||
bufferedReader.close();
|
||||
}
|
||||
if (connection != null) {
|
||||
connection.disconnect();
|
||||
}
|
||||
} catch (Exception e2) {
|
||||
XxlJobLogger.log(e2);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -1,36 +0,0 @@
|
||||
package com.xuxueli.executor.sample.frameless.jobhandler;
|
||||
|
||||
import com.xxl.job.core.biz.model.ReturnT;
|
||||
import com.xxl.job.core.context.XxlJobContext;
|
||||
import com.xxl.job.core.handler.IJobHandler;
|
||||
import com.xxl.job.core.log.XxlJobLogger;
|
||||
|
||||
/**
|
||||
* 分片广播任务
|
||||
*
|
||||
* @author xuxueli 2017-07-25 20:56:50
|
||||
*/
|
||||
public class ShardingJobHandler extends IJobHandler {
|
||||
|
||||
@Override
|
||||
public ReturnT<String> execute(String param) throws Exception {
|
||||
|
||||
// 分片参数
|
||||
int shardIndex = XxlJobContext.getXxlJobContext().getShardIndex();
|
||||
int shardTotal = XxlJobContext.getXxlJobContext().getShardTotal();
|
||||
|
||||
XxlJobLogger.log("分片参数:当前分片序号 = {}, 总分片数 = {}", shardIndex, shardTotal);
|
||||
|
||||
// 业务逻辑
|
||||
for (int i = 0; i < shardTotal; i++) {
|
||||
if (i == shardIndex) {
|
||||
XxlJobLogger.log("第 {} 片, 命中分片开始处理", i);
|
||||
} else {
|
||||
XxlJobLogger.log("第 {} 片, 忽略", i);
|
||||
}
|
||||
}
|
||||
|
||||
return SUCCESS;
|
||||
}
|
||||
|
||||
}
|
@ -1,6 +1,6 @@
|
||||
package com.xuxueli.executor.sample.frameless;
|
||||
package com.xxl.job.executor.sample.frameless;
|
||||
|
||||
import com.xuxueli.executor.sample.frameless.config.FrameLessXxlJobConfig;
|
||||
import com.xxl.job.executor.sample.frameless.config.FrameLessXxlJobConfig;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
@ -1,44 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>com.xuxueli</groupId>
|
||||
<artifactId>xxl-job-executor-samples</artifactId>
|
||||
<version>2.3.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>xxl-job-executor-sample-jfinal</artifactId>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<dependencies>
|
||||
<!-- jfinal -->
|
||||
<dependency>
|
||||
<groupId>com.jfinal</groupId>
|
||||
<artifactId>jfinal-undertow</artifactId>
|
||||
<version>2.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.jfinal</groupId>
|
||||
<artifactId>jfinal</artifactId>
|
||||
<version>4.9.02</version>
|
||||
</dependency>
|
||||
|
||||
<!-- slf4j -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-log4j12</artifactId>
|
||||
<version>${slf4j-api.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- xxl-job -->
|
||||
<dependency>
|
||||
<groupId>com.xuxueli</groupId>
|
||||
<artifactId>xxl-job-core</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
@ -1,12 +0,0 @@
|
||||
package com.xuxueli.executor.sample.jfinal;
|
||||
|
||||
import com.jfinal.server.undertow.UndertowServer;
|
||||
import com.xuxueli.executor.sample.jfinal.config.JFinalCoreConfig;
|
||||
|
||||
public class XxlJobExecutorApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
UndertowServer.start(JFinalCoreConfig.class, 8082, true);
|
||||
}
|
||||
|
||||
}
|
@ -1,85 +0,0 @@
|
||||
package com.xuxueli.executor.sample.jfinal.config;
|
||||
|
||||
import com.jfinal.config.*;
|
||||
import com.jfinal.kit.Prop;
|
||||
import com.jfinal.kit.PropKit;
|
||||
import com.jfinal.template.Engine;
|
||||
import com.xuxueli.executor.sample.jfinal.controller.IndexController;
|
||||
import com.xuxueli.executor.sample.jfinal.jobhandler.CommandJobHandler;
|
||||
import com.xuxueli.executor.sample.jfinal.jobhandler.DemoJobHandler;
|
||||
import com.xuxueli.executor.sample.jfinal.jobhandler.HttpJobHandler;
|
||||
import com.xuxueli.executor.sample.jfinal.jobhandler.ShardingJobHandler;
|
||||
import com.xxl.job.core.executor.XxlJobExecutor;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* @author xuxueli 2017-08-11 14:17:41
|
||||
*/
|
||||
public class JFinalCoreConfig extends JFinalConfig {
|
||||
private Logger logger = LoggerFactory.getLogger(JFinalCoreConfig.class);
|
||||
|
||||
// ---------------------- xxl-job executor ----------------------
|
||||
private XxlJobExecutor xxlJobExecutor = null;
|
||||
private void initXxlJobExecutor() {
|
||||
|
||||
// registry jobhandler
|
||||
XxlJobExecutor.registJobHandler("demoJobHandler", new DemoJobHandler());
|
||||
XxlJobExecutor.registJobHandler("shardingJobHandler", new ShardingJobHandler());
|
||||
XxlJobExecutor.registJobHandler("httpJobHandler", new HttpJobHandler());
|
||||
XxlJobExecutor.registJobHandler("commandJobHandler", new CommandJobHandler());
|
||||
|
||||
// load executor prop
|
||||
Prop xxlJobProp = PropKit.use("xxl-job-executor.properties");
|
||||
|
||||
// init executor
|
||||
xxlJobExecutor = new XxlJobExecutor();
|
||||
xxlJobExecutor.setAdminAddresses(xxlJobProp.get("xxl.job.admin.addresses"));
|
||||
xxlJobExecutor.setAccessToken(xxlJobProp.get("xxl.job.accessToken"));
|
||||
xxlJobExecutor.setAddress(xxlJobProp.get("xxl.job.executor.address"));
|
||||
xxlJobExecutor.setAppname(xxlJobProp.get("xxl.job.executor.appname"));
|
||||
xxlJobExecutor.setIp(xxlJobProp.get("xxl.job.executor.ip"));
|
||||
xxlJobExecutor.setPort(xxlJobProp.getInt("xxl.job.executor.port"));
|
||||
|
||||
xxlJobExecutor.setLogPath(xxlJobProp.get("xxl.job.executor.logpath"));
|
||||
xxlJobExecutor.setLogRetentionDays(xxlJobProp.getInt("xxl.job.executor.logretentiondays"));
|
||||
|
||||
// start executor
|
||||
try {
|
||||
xxlJobExecutor.start();
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
private void destoryXxlJobExecutor() {
|
||||
if (xxlJobExecutor != null) {
|
||||
xxlJobExecutor.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------- jfinal ----------------------
|
||||
|
||||
@Override
|
||||
public void onStart() {
|
||||
initXxlJobExecutor();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStop() {
|
||||
destoryXxlJobExecutor();
|
||||
}
|
||||
|
||||
public void configConstant(Constants me) {
|
||||
me.setDevMode(true);
|
||||
}
|
||||
|
||||
public void configRoute(Routes routes) {
|
||||
routes.add("/", IndexController.class);
|
||||
}
|
||||
|
||||
public void configEngine(Engine me) {}
|
||||
public void configPlugin(Plugins me) {}
|
||||
public void configInterceptor(Interceptors me) {}
|
||||
public void configHandler(Handlers me) {}
|
||||
|
||||
}
|
@ -1,11 +0,0 @@
|
||||
package com.xuxueli.executor.sample.jfinal.controller;
|
||||
|
||||
import com.jfinal.core.Controller;
|
||||
|
||||
public class IndexController extends Controller {
|
||||
|
||||
public void index(){
|
||||
renderText("xxl job executor running.");
|
||||
}
|
||||
|
||||
}
|
@ -1,54 +0,0 @@
|
||||
package com.xuxueli.executor.sample.jfinal.jobhandler;
|
||||
|
||||
import com.xxl.job.core.biz.model.ReturnT;
|
||||
import com.xxl.job.core.handler.IJobHandler;
|
||||
import com.xxl.job.core.log.XxlJobLogger;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
/**
|
||||
* 命令行任务
|
||||
*
|
||||
* @author xuxueli 2018-09-16 03:48:34
|
||||
*/
|
||||
public class CommandJobHandler extends IJobHandler {
|
||||
|
||||
@Override
|
||||
public ReturnT<String> execute(String param) throws Exception {
|
||||
String command = param;
|
||||
int exitValue = -1;
|
||||
|
||||
BufferedReader bufferedReader = null;
|
||||
try {
|
||||
// command process
|
||||
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) {
|
||||
XxlJobLogger.log(line);
|
||||
}
|
||||
|
||||
// command exit
|
||||
process.waitFor();
|
||||
exitValue = process.exitValue();
|
||||
} catch (Exception e) {
|
||||
XxlJobLogger.log(e);
|
||||
} finally {
|
||||
if (bufferedReader != null) {
|
||||
bufferedReader.close();
|
||||
}
|
||||
}
|
||||
|
||||
if (exitValue == 0) {
|
||||
return IJobHandler.SUCCESS;
|
||||
} else {
|
||||
return new ReturnT<String>(IJobHandler.FAIL.getCode(), "command exit value("+exitValue+") is failed");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,121 +0,0 @@
|
||||
package com.xuxueli.executor.sample.jfinal.jobhandler;
|
||||
|
||||
import com.xxl.job.core.biz.model.ReturnT;
|
||||
import com.xxl.job.core.handler.IJobHandler;
|
||||
import com.xxl.job.core.log.XxlJobLogger;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* 跨平台Http任务
|
||||
*
|
||||
* @author xuxueli 2018-09-16 03:48:34
|
||||
*/
|
||||
public class HttpJobHandler extends IJobHandler {
|
||||
|
||||
@Override
|
||||
public ReturnT<String> execute(String param) throws Exception {
|
||||
|
||||
// param parse
|
||||
if (param==null || param.trim().length()==0) {
|
||||
XxlJobLogger.log("param["+ param +"] invalid.");
|
||||
return ReturnT.FAIL;
|
||||
}
|
||||
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) {
|
||||
XxlJobLogger.log("url["+ url +"] invalid.");
|
||||
return ReturnT.FAIL;
|
||||
}
|
||||
if (method==null || !Arrays.asList("GET", "POST").contains(method)) {
|
||||
XxlJobLogger.log("method["+ method +"] invalid.");
|
||||
return ReturnT.FAIL;
|
||||
}
|
||||
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();
|
||||
|
||||
XxlJobLogger.log(responseMsg);
|
||||
return ReturnT.SUCCESS;
|
||||
} catch (Exception e) {
|
||||
XxlJobLogger.log(e);
|
||||
return ReturnT.FAIL;
|
||||
} finally {
|
||||
try {
|
||||
if (bufferedReader != null) {
|
||||
bufferedReader.close();
|
||||
}
|
||||
if (connection != null) {
|
||||
connection.disconnect();
|
||||
}
|
||||
} catch (Exception e2) {
|
||||
XxlJobLogger.log(e2);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -1,36 +0,0 @@
|
||||
package com.xuxueli.executor.sample.jfinal.jobhandler;
|
||||
|
||||
import com.xxl.job.core.biz.model.ReturnT;
|
||||
import com.xxl.job.core.context.XxlJobContext;
|
||||
import com.xxl.job.core.handler.IJobHandler;
|
||||
import com.xxl.job.core.log.XxlJobLogger;
|
||||
|
||||
/**
|
||||
* 分片广播任务
|
||||
*
|
||||
* @author xuxueli 2017-07-25 20:56:50
|
||||
*/
|
||||
public class ShardingJobHandler extends IJobHandler {
|
||||
|
||||
@Override
|
||||
public ReturnT<String> execute(String param) throws Exception {
|
||||
|
||||
// 分片参数
|
||||
int shardIndex = XxlJobContext.getXxlJobContext().getShardIndex();
|
||||
int shardTotal = XxlJobContext.getXxlJobContext().getShardTotal();
|
||||
|
||||
XxlJobLogger.log("分片参数:当前分片序号 = {}, 总分片数 = {}", shardIndex, shardTotal);
|
||||
|
||||
// 业务逻辑
|
||||
for (int i = 0; i < shardTotal; i++) {
|
||||
if (i == shardIndex) {
|
||||
XxlJobLogger.log("第 {} 片, 命中分片开始处理", i);
|
||||
} else {
|
||||
XxlJobLogger.log("第 {} 片, 忽略", i);
|
||||
}
|
||||
}
|
||||
|
||||
return SUCCESS;
|
||||
}
|
||||
|
||||
}
|
@ -1,27 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE log4j:configuration PUBLIC "-//log4j/log4j Configuration//EN" "log4j.dtd">
|
||||
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" threshold="null" debug="null">
|
||||
|
||||
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
|
||||
<param name="Target" value="System.out" />
|
||||
<layout class="org.apache.log4j.PatternLayout">
|
||||
<param name="ConversionPattern" value="%-d{yyyy-MM-dd HH:mm:ss} xxl-job-executor-sample-jfinal [%c]-[%t]-[%M]-[%L]-[%p] %m%n"/>
|
||||
</layout>
|
||||
</appender>
|
||||
|
||||
<appender name="FILE" class="org.apache.log4j.DailyRollingFileAppender">
|
||||
<param name="file" value="/data/applogs/xxl-job/xxl-job-executor-sample-jfinal.log"/>
|
||||
<param name="append" value="true"/>
|
||||
<param name="encoding" value="UTF-8"/>
|
||||
<layout class="org.apache.log4j.PatternLayout">
|
||||
<param name="ConversionPattern" value="%-d{yyyy-MM-dd HH:mm:ss} xxl-job-executor-sample-jfinal [%c]-[%t]-[%M]-[%L]-[%p] %m%n"/>
|
||||
</layout>
|
||||
</appender>
|
||||
|
||||
<root>
|
||||
<level value="INFO" />
|
||||
<appender-ref ref="CONSOLE" />
|
||||
<appender-ref ref="FILE" />
|
||||
</root>
|
||||
|
||||
</log4j:configuration>
|
@ -1,17 +0,0 @@
|
||||
### xxl-job admin address list, such as "http://address" or "http://address01,http://address02"
|
||||
xxl.job.admin.addresses=http://127.0.0.1:8080/xxl-job-admin
|
||||
|
||||
### xxl-job, access token
|
||||
xxl.job.accessToken=
|
||||
|
||||
### xxl-job executor appname
|
||||
xxl.job.executor.appname=xxl-job-executor-sample
|
||||
### xxl-job executor registry-address: default use address to registry , otherwise use ip:port if address is null
|
||||
xxl.job.executor.address=
|
||||
### xxl-job executor server-info
|
||||
xxl.job.executor.ip=
|
||||
xxl.job.executor.port=9999
|
||||
### xxl-job executor log-path
|
||||
xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler
|
||||
### xxl-job executor log-retention-days
|
||||
xxl.job.executor.logretentiondays=30
|
@ -1,32 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
|
||||
id="WebApp_ID" version="2.5">
|
||||
|
||||
<display-name>xxl-job-executor-sample-jfinal</display-name>
|
||||
<context-param>
|
||||
<param-name>webAppRootKey</param-name>
|
||||
<param-value>xxl-job-executor-sample-jfinal</param-value>
|
||||
</context-param>
|
||||
|
||||
<!-- jfinal -->
|
||||
<filter>
|
||||
<filter-name>jfinal</filter-name>
|
||||
<filter-class>com.jfinal.core.JFinalFilter</filter-class>
|
||||
<init-param>
|
||||
<param-name>configClass</param-name>
|
||||
<param-value>com.xuxueli.executor.sample.jfinal.config.JFinalCoreConfig</param-value>
|
||||
</init-param>
|
||||
</filter>
|
||||
<filter-mapping>
|
||||
<filter-name>jfinal</filter-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</filter-mapping>
|
||||
|
||||
|
||||
<welcome-file-list>
|
||||
<welcome-file>index.html</welcome-file>
|
||||
</welcome-file-list>
|
||||
|
||||
</web-app>
|
@ -1 +0,0 @@
|
||||
i am alive.
|
Loading…
Reference in new issue