最近有个小伙伴问我,我们的项目核心业务的地方总是有异常,虽然有打印日志,但不能立马通知我;所以今天我就教大家如何实现异常报警实时提醒
1.需要有钉钉
自己新建的企业用户
2.建一个群,需要有三人以上;点击机器人
3.自定义机器人里面设置key和秘钥
key
3.发送消息的java代码
@Slf4j
public class MessageWarningUtils {public static void sendMessage(String error, String token, String secretKey) {try {OapiRobotSendRequest request = new OapiRobotSendRequest();OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();sendMarkdown(request, markdown, error);DingTalkClient client = new DefaultDingTalkClient(token + sign(secretKey));OapiRobotSendResponse response = client.execute(request);if (response != null && response.getErrcode() != 0) {throw new CustomException("系统触发钉钉流控!");}} catch (Exception e) {log.error("系统发送钉钉消息失败=", e);}}private static String sign(String dingTalkSecretKey) {try {Long timestamp = System.currentTimeMillis();String stringToSign = timestamp + "\n" + dingTalkSecretKey;Mac mac = Mac.getInstance("HmacSHA256");mac.init(new SecretKeySpec(dingTalkSecretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");return "×tamp=" + timestamp + "&sign=" + sign;} catch (Exception e) {log.error("系统钉钉消息提醒签名异常=", e);}return "";}/*** 发送markdown文档格式*/public static void sendMarkdown(OapiRobotSendRequest request, OapiRobotSendRequest.Markdown markdown, String error) {request.setMsgtype("markdown");markdown.setTitle("平台告警");markdown.setText("### @所有人 \n" +"### **异常信息:** " + error + "\n\n");OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();at.setIsAtAll(false);List<String> mobiles = new ArrayList<>();mobiles.add("所有人");at.setAtUserIds(mobiles);request.setAt(at);request.setMarkdown(markdown);}
}
4.获取钉钉的key和签名
建机器人的时候,有截图 key和签名,放在你的项目配置文件里面就可以拿到了
@Component
public class DingDingConfig {@Resourceprivate Environment environment;public String getToken() {return environment.getProperty("dingding.warning.token");}public String getSecretKey() {return environment.getProperty("dingding.warning.secretKey");}public String getToken2() {return environment.getProperty("dingding.warning2.token");}public String getSecretKey2() {return environment.getProperty("dingding.warning2.secretKey");}
}
5.测试异常消息发送
@Resourceprivate DingDingConfig dingDingConfig;public static void main(String[] args) {try {throw new RuntimeException("我就故意报错");}catch (Exception e){MessageWarningUtils.sendMessage("应付账单下载异常=" + e, dingDingConfig.getToken(), dingDingConfig.getSecretKey());}}
dingDingConfig 有可能报错,你重新设置下就好了
6.结果
有问题,请留言讨论
项目发消息的过程中有可能会报IP白名单问题,大家可以去百度的钉钉的相关配置下,设置下就好了