xxl-job集成钉钉群告警
xxl-job集成钉钉群告警
1.申请钉钉群机器人webhook
- 钉钉群里添加智能群助手
- 添加机器人
- 选择自定义(通过webhook接入自定义服务)
- 给机器人起个名字,再进行下安全设置,我选择的是自定义关键词(发送的消息带关键词就能成功发送)
- 得到webhook的url,保存下来
2.配置xxl-job的application.properties
添加如下配置:
#dingding webhook
dingding.robot.webhook.url=https://oapi.dingtalk.com/robot/send?access_token=xxxxx
dingding.robot.webhook.keyword=xxl-job
3.编写告警通知代码
如何跑起来xxl-job项目这里不再额外说明
使用的xxl-job版本是2.3.1
官方文档
5.16 任务失败告警
默认提供邮件失败告警,可扩展短信、钉钉等方式。如果需要新增一种告警方式,只需要新增一个实现 “com.xxl.job.admin.core.alarm.JobAlarm” 接口的告警实现即可。可以参考默认提供邮箱告警实现 “EmailJobAlarm”。
在xxl-job的com.xxl.job.admin.core.alarm.impl包里添加我们代码:
package com.xxl.job.admin.core.alarm.impl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxl.job.admin.core.alarm.JobAlarm;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* 实现钉钉机器人报警<br>
* <a href ='https://open.dingtalk.com/document/robots/custom-robot-access'>钉钉文档</a>
*
* @author jhd
* @since 2022-8-9
*/
@Component
public class DingDingJobAlarm implements JobAlarm, InitializingBean, DisposableBean {
private static final Logger logger = LoggerFactory.getLogger(DingDingJobAlarm.class);
@Value("${dingding.robot.webhook.url}")
private String webhookUrl;
@Value("${dingding.robot.webhook.keyword}")
private String keyword;
@Autowired
private ObjectMapper om;
@Value("${server.port}")
private String port;
@Override
public boolean doAlarm(XxlJobInfo info, XxlJobLog jobLog) {
logger.info("钉钉告警开始 jobLog.id:{}", jobLog.getId());
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
StringBuilder content = new StringBuilder();
//我们设置了消息关键字,先放入关键字
content.append(keyword).append("任务失败!\n");
content.append("负责人:").append(info.getAuthor()).append("\n");
content.append("任务描述:").append(info.getJobDesc()).append("\n");
content.append("JobId:").append(jobLog.getJobId()).append("\n");
content.append("JobGroup:").append(jobLog.getJobGroup()).append("\n");
content.append("执行器名称:").append(info.getExecutorHandler()).append("\n");
content.append("执行器ip:").append(jobLog.getExecutorAddress()).append("\n");
content.append("任务参数:").append(jobLog.getExecutorParam()).append("\n");
content.append("LogId:").append(jobLog.getId()).append("\n");
content.append("告警时间:").append(sdf.format(new Date())).append("\n");
if (jobLog.getTriggerTime() != null) {
content.append("TriggerTime:").append(sdf.format(jobLog.getTriggerTime())).append("\n");
}
String msg = jobLog.getTriggerMsg();
if (null != msg && !"".equals(msg.trim())) {
msg = msg.replace("<br>", "\n");
content.append("TriggerMsg:").append(msg).append("\n");
}
if (jobLog.getHandleTime() != null) {
content.append("HandleTime:").append(sdf.format(jobLog.getHandleTime())).append("\n");
}
String handleMsg = jobLog.getHandleMsg();
if (null != handleMsg && !"".equals(handleMsg.trim())) {
//去掉多余的制表符,为了显示简洁
handleMsg = handleMsg.replace("\r", "").replace("\t", "");
content.append("HandleMsg:").append(handleMsg).append("\n");
}
Map<String, Object> textMessage = buildTextMessage(content.toString());
//推送消息(http请求)
String result = postJson(webhookUrl, textMessage);
logger.info("钉钉告警结果 jobLog.id:{} result:{}", jobLog.getId(), result);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 官方text类型消息格式
* <pre>
* {
* "at": {
* "atMobiles":[
* "180xxxxxx"
* ],
* "atUserIds":[
* "user123"
* ],
* "isAtAll": false
* },
* "text": {
* "content":"我就是我, @XXX 是不一样的烟火"
* },
* "msgtype":"text"
* }
* </pre>
*/
private Map<String, Object> buildTextMessage(String content) {
//消息内容
HashMap<String, String> contentMap = new HashMap<>();
contentMap.put("content", content);
//通知人
HashMap<String, Object> atMap = new HashMap<>();
//1.是否通知所有人
atMap.put("isAtAll", false);
//2.通知具体人的手机号码列表
List<String> mobileList = new ArrayList<>();
atMap.put("atMobiles", mobileList);
//3.用户id
List<String> userIdList = new ArrayList<>();
atMap.put("atUserIds", userIdList);
Map<String, Object> messageMap = new HashMap<>();
messageMap.put("msgtype", "text");
messageMap.put("text", contentMap);
messageMap.put("at", atMap);
return messageMap;
}
/**
* 成功返回的格式是:{"errcode":0,"errmsg":"ok"}
* <br>
* 其他情况都是失败
*/
private String postJson(String url, Map<String, Object> message) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
//不设置ContentType会返回{"errcode":43004,"errmsg":"无效的HTTP HEADER Content-Type"}
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> request = new HttpEntity<>(message, headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);
String body = responseEntity.getBody();
JsonNode jsonNode = null;
try {
jsonNode = om.readTree(body);
JsonNode errcodeNode = jsonNode.get("errcode");
int errcode = errcodeNode.asInt(-1);
HttpStatus statusCode = responseEntity.getStatusCode();
if (statusCode != HttpStatus.OK || errcode != 0) {
throw new RuntimeException("钉钉webhook调用失败!\r\n" +
"statusCode:" + statusCode.toString() + "\r\n" +
"body:" + body);
}
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return body;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.hasLength(webhookUrl, "dingding.robot.webhook.url must not be empty");
Assert.hasLength(keyword, "dingding.robot.webhook.keyword must not be empty");
Map<String, Object> textMessage = buildTextMessage("xxl-job服务已启动 端口:" + port);
String s = postJson(webhookUrl, textMessage);
logger.info("钉钉机器人告警已上线:{}", s);
}
@Override
public void destroy() throws Exception {
Map<String, Object> textMessage = buildTextMessage("xxl-job服务已停止 端口:" + port);
String s = postJson(webhookUrl, textMessage);
logger.info("钉钉机器人告警已下线:{}", s);
}
}
不仅实现了告警通知了,也通过bean的生命周期实现了xxl-job的上线,下线通知;
使用的工具类都是spring boot自带的;
4.测试,然后观察群消息
启动项目
xxl-job服务已启动 端口:8080
模拟异常任务(直接在任务中抛RuntimeException即可)
xxl-job任务失败!
负责人:jhd
任务描述:test1
JobId:7
JobGroup:4
执行器名称:test1
执行器ip:http://192.168.5.17:9999/
任务参数:
LogId:86
告警时间:2022-08-10 09:20:41
TriggerTime:2022-08-10 09:20:38
TriggerMsg:任务触发类型:手动触发
调度机器:192.168.5.17
执行器-注册方式:自动注册
执行器-地址列表:[http://192.168.5.17:9999/]
路由策略:第一个
阻塞处理策略:单机串行
任务超时时间:0
失败重试次数:0
>>>>>>>>>>>触发调度<<<<<<<<<<<
触发调度:
address:http://192.168.5.17:9999/
code:200
msg:null
HandleTime:2022-08-10 09:20:38
HandleMsg:java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.xxl.job.core.handler.impl.MethodJobHandler.execute(MethodJobHandler.java:31)
at com.xxl.job.core.thread.JobThread.run(JobThread.java:166)
Caused by: java.lang.RuntimeException: 测试异常
at com.gooinfo.xxljobclient.task.TestTask.test1(TestTask.java:12)
… 6 more
停止项目
xxl-job服务已停止 端口:8080
5.写在最后
代码并没有实现@功能,如果需要还请自行添加。通知也没处理xxl-job的日志,如需获取还请自行搜索。
总体还是较为简单的,有问题通过官方文档或者搜索引擎搜索都能解决。
更多推荐
所有评论(0)