任务失败告警
定时任务调用失败,发送通知给某人
定义接收通知服务请求
定义服务请求,请求方法 POST。
请求参数
- jobid 为任务 ID,调用时使用调度中心的环境变量 ${jobId} 获取
- executeNumber 为执行次数,调用时使用调度中心的环境变量 ${executeNumber} 获取
- 请求体参数是必须的,为调度中心发送过来的定时任务执行情况,结构如下
{
"httpStatus": "200", //http 的返回状态码
"response": {
"status": "failed", //任务状态: failed——失败 succeed——成功 finalFailed——最终失败 finalSucceed——最终成功
"message": "同步调用request成功...", //提示信息
"error": "error1", //
"progress": "30%", //任务进度
"data": {} //定时服务返回的数据
}
}
从市场下载 jobsClient 组件
设置依赖
引入 com.justep.cloud jobs-client 1.0.0 包
写代码
同步定时任务调度中心返回示例如下
{
"response": {
"data": {
"data": "OK"//定时任务返回的数据
},
"progress": "100%",
"message": "同步调用request成功...",
"status": "finalSucceed"
},
"httpStatus": 200
}
异步定时任务,返回信息由 checkUrl 或 feedbackUrl 返回。
接收通知服务的逻辑是:从调度中心返回的结果中获取任务执行情况,判断状态为最终失败(也可以根据定时任务返回的数据进行判断)则发送消息,代码如下
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.justep.cloud.job.client.common.entity.HttpInvokeResult;
import com.justep.util.SpringWebUtil;
import com.justep.util.net.ServiceUtil;
public String receiveNotify(String results,String jobId,String executeNumber) throws Exception {
//从调度中心返回的结果中获取任务执行情况
HttpInvokeResult ret = JSON.parseObject(results, HttpInvokeResult.class);
int httpStatus = ret.getHttpStatus();
Object res = ret.getResponse();
Map entity = (Map)res;
String data = "";
if(entity.get("data")!=null){
data=entity.get("data").toString();
}
String progress = entity.get("progress").toString();
String message = entity.get("message").toString();
String status = entity.get("status").toString();
System.out.println("jobId-->"+ jobId);
System.out.println("executeNumber-->"+ executeNumber);
String jsonStr = JSON.toJSONString(results);
System.out.println("notify context--->" + jsonStr);
System.out.println("data-->"+ data);
System.out.println("progress-->"+ progress);
System.out.println("message-->"+ message);
System.out.println("status-->"+ status);
//定时任务失败,发送消息
if("finalFailed".equals(status) || "failed".equals(status)){
JSONObject title = new JSONObject();
title.put("title", "定时任务测试");
title.put("message", message);
JSONObject params = new JSONObject();
params.put("templateCode", "TIMER_WARN_MESSAGE");
params.put("senderId", "system");
params.put("senderName", "system");
params.put("params", title);
ServiceUtil.post(SpringWebUtil.getRequest(), "message", "/main/message/sendmessage", params);
}
return "OK";
}
上面的代码执行后输出如下
jobId-->CA2B296065700001687EA002191B2FA0
executeNumber-->1
notify context--->"{\"response\":{\"data\":{\"data\":\"OK\"},\"progress\":\"100%\",\"message\":\"同步调用request成功...\",\"status\":\"finalSucceed\"},\"httpStatus\":200}"
data-->{"data":"OK"}
progress-->100%
message-->同步调用request成功...
status-->finalSucceed
配置消息模板
代码中的 TIMER_WARN_MESSAGE 为消息模板编码,在消息中心的消息模板管理中配置,如下图所示
- 标题和内容中可以使用变量,用 ${变量名} 的方式引用,请求参数 params 里面需包含变量值
- 可配置发送方式和接收者
配置通知请求模板
在定时任务上配置通知请求模板
选择接受通知服务,使用调度中心提供的两个环境变量设置两个参数
可以设置匹配策略,不同的状态调用不同的服务请求。本例没有设置匹配策略,是在代码中判断的