Git地址:https://github.com/xuxueli/xxl-job
详细文档:https://www.xuxueli.com/xxl-job/
项目应用总结(修改源码支持部分成功状态):
1.项目的pom.xml中引用xxl-job
<!-- xxl-job-core --> <dependency> <groupId>com.xuxueli</groupId> <artifactId>xxl-job-core</artifactId> </dependency>
2.添加相关配置节点
### xxl-job admin address list, such as "http://address" or "http://address01,http://address02" xxl: job: admin: addresses: http://192.168.10.205:8091/jmgo-job-admin accessToken: executor: appname: tandemplatform-schedule address: ip: port: 9200 logpath: /logs/ logretentiondays: 30
3.按固定入参返回值编写Job
/** * 发送邮件 */ @XxlJob("sendVipMails") public ReturnT<String> sendVipMails(String param) throws Exception { sendMails(); return ReturnT.SUCCESS; }
4.记录开始结束日志
@Aspect @Component public class XxlJoblogAop { @Pointcut("@annotation(com.xxl.job.core.handler.annotation.XxlJob)") public void xxlJoblog() {} //@annotation(anno) 里的必须和方法名参数名一致才可以获取到注解里的值, //这里目的是使用@XxlJob注解里的值,方法执行结束后从当前ThreadLocal获取是否全部成功或失败,若为false则返回部分成功 @Around("xxlJoblog() && @annotation(anno)") public Object doAround(ProceedingJoinPoint pjp, XxlJob anno) { long st = System.currentTimeMillis(); Object proceed = null; String value = anno.value(); ThreadLocalUtil.set(value,ReturnT.SUCCESS); //此处设置value为ReturnT.SUCCESS XxlJobLogger.log(value + " >>>>>---JOB START--->>>>>"); try { proceed = pjp.proceed(); //执行方法 } catch (Throwable throwable) { throwable.printStackTrace(); } XxlJobLogger.log(value + " <<<<<----JOB END---<<<<<"); XxlJobLogger.log("任务共计耗时:{}ms",System.currentTimeMillis() - st); ReturnT result = (ReturnT) proceed; //如果没有被标注为部分成功,或者方法返回FAIL,那么不改变其执行状态 return ThreadLocalUtil.get(value,ReturnT.class)!=ReturnT.PARTITIAL_SUC ||result==ReturnT.FAIL ? proceed:ReturnT.PARTITIAL_SUC; } }
5.记录每步执行的情况(报错时,同时需要使用 log.error 记录到日志里)
for (var info : infos){
try {
var payOrder =payOrderService.getById(info);
JSONObject syncMesJson = new JSONObject();
boolean syncFlag = payOrderService.syncMesPayRecord(syncMesJson);
if(syncFlag){
payOrderService.updateIsSyncMes(payOrder.getId());
XxlJobLogger.log("支付成功通知MES消息重发成功,订单ID:{}",info);
}
else {
XxlJobLogger.log("支付成功通知MES消息重发失败,订单ID:{}",info);
count.getAndIncrement();
}
}catch (Exception ex) {
ThreadLocalUtil.set("sendVipMails",false);
count.getAndIncrement();
XxlJobLogger.log("支付成功通知MES消息重发失败,订单ID:{},错误信息:{}",info,ex.getStackTrace());
log.error("支付成功通知MES消息重发失败,订单ID:{},错误信息:{}",info,ex.getStackTrace());
}
}
String result = MessageFormat.format("本次循环共【{}】条,执行异常【{}】条,成功执行【{}】条",size,count,size- count.get());
XxlJobLogger.log(result);
if(size>0)
return new ReturnT(200,result);
else
return ReturnT.SUCCESS;