监控告警:钉钉告警 【钉钉机器人发送消息,集成SpringBoot】
实现步骤
钉钉开发平台-自定义机器人接入文档:https://open.dingtalk.com/document/group/custom-robot-access
通过调用Webhook地址可将告警消息发送到群聊里来实现消息通知的功能
1、创建钉钉群
2、添加群机器人
注意:选择其中一项安全设置,可加强安全性,防止Webhook地址泄密被乱发消息
3、 创建成功,复制Webhook地址
注意:请保管好此Webhook 地址,不要公布在外部网站上,泄露后有安全风险。
设计与实现
前端页面设计
java实现
public static void main(String[] args) {
try {
//注意:添加机器人时安全设置选择“加签”时,需要计算签名,并把timestamp和第一步得到的签名值拼接到URL中
Long timestamp = System.currentTimeMillis();
//加签一栏下面显示的SEC开头的字符串。
String secret = "SEC4202dae12290ae7137ef25xxxxxxxxxxxxxxxxxxx";
String sign = getSign(timestamp,secret);
//钉钉机器人地址(配置机器人的webhook)
String dingUrl = "https://oapi.dingtalk.com/robot/send?access_token=b4bbf11c9bfc63936d625xxxxxxxxxxxxxxxxxxx×tamp="+timestamp+"&sign="+sign;
//注意:isAtAll【通知所有人】和 mobileList【通知具体人的手机号码列表】 不能同时生效
//是否通知所有人
boolean isAtAll = false;
//通知具体人的手机号码列表
List mobileList = Lists.newArrayList();
mobileList.add("153xxxxxxx");
mobileList.add("1500xxxxxx");
//钉钉机器人消息内容
// 注意:添加机器人时安全设置选择的是自定义关键词时,发送内容要包含设置的关键字
String content = "ipsec业务告警:哈哈,你好!,这是测试机器人消息 啦啦啦啦啦了 使用签名";
//组装请求内容
String reqStr = buildReqStr(content, isAtAll, mobileList);
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity request = new HttpEntity<>(reqStr, headers);
ResponseEntity postForEntity = restTemplate.postForEntity(dingUrl, request, String.class);
String body = String.valueOf(postForEntity.getBody());
System.out.println(body);
} catch (Exception e) {
e.printStackTrace();
}
}
//** 组装请求报文 *//*
private static String buildReqStr(String content, boolean isAtAll, List mobileList) {
//消息内容
Map contentMap = Maps.newHashMap();
contentMap.put("content", content);
//通知人
Map atMap = Maps.newHashMap();
//1.是否通知所有人
atMap.put("isAtAll", isAtAll);
//2.通知具体人的手机号码列表
atMap.put("atMobiles", mobileList);
Map reqMap = Maps.newHashMap();
reqMap.put("msgtype", "text");
reqMap.put("text", contentMap);
reqMap.put("at", atMap);
return JsonUtil.toStr(reqMap);
}
/**计算签名**/
public static String getSign(Long timestamp, String secret) throws Exception{
String stringToSign = timestamp + "\n" + secret;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
System.out.println(sign);
return sign;
}