官方对接地址
https://developers.dingtalk.com/document/app/custom-robot-access
第一步:拉一个钉钉群,然后添加一个机器人,获取发送权限
添加完成后,会返回发送的地址链接:
https://oapi.dingtalk.com/robot/send?access_token=xxxx
注意点:发送内容必须含有自定义关键词,才能发送成功
第二步:编写发送钉钉消息代码
注意点:content中必须含有 第一步设置的关键词 “告警” 两个字否则发送不成功。
@Component
@Slf4j
public class DingDingHelper {
@Resource
private RestTemplate restTemplate;
@Autowired
private EnvHelper envHelper;
@Async
public void sendAlert(String title, String context) {
try {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("【类型】: ").append("某某项目业务告警").append("\n");
stringBuffer.append("【标题】: ").append(title).append("\n");
stringBuffer.append("【环境】: ").append(envHelper.getEnv()).append("\n");
stringBuffer.append("【链路id】: ").append(TraceContext.traceId()).append("\n");
stringBuffer.append("【内容】: ").append( context).append("\n");
stringBuffer.append("【时间】: ").append(DateTimeUtils.toString(LocalDateTime.now())).append("\n");
HashMap<String, Object> text = new HashMap<>(2);
text.put("content", stringBuffer.toString());
HashMap<String, Object> params = new HashMap<>(4);
params.put("msgtype", "text");
params.put("text", text);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
restTemplate.postForEntity("https://oapi.dingtalk.com/robot/send?access_token=xxx",
new HttpEntity<>(params, headers), Void.class);
} catch (RestClientException e) {
log.error("发送钉钉异常={}", e.getMessage());
}
}
}
将发送钉钉消息,结合项目和环境链路,可以在程序中打点告警,方便问题及时人工处理和问题的排查。