maven引入dinger依赖
<dependency>
<groupId>com.github.answerail</groupId>
<artifactId>dinger-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
dinger application.yml配置
spring:
dinger:
project-id: ${spring.application.name}
dingers:
# 使用钉钉机器人
dingtalk:
token-id: 87dbeb7bc28894c3ycyl3d12457228ad309966275b5f427cd85f9025ebb520cf
secret: AEQ74a9039ai01f2ljm017b90ycye9asg6335f97c658ff37ff371ec8120581c7f09
注意根据实际机器人配置信息进行修改
扩展:使用企业微信钉钉机器人配置
spring:
dinger:
project-id: ${spring.application.name}
dingers:
wetalk:
token-id: 32865206-7082-46l5-8j39-2m7ycy6d856
使用Dinger
方式1-显示发送方式
@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalController {
@Autowired
private DingerSender dingerSender;
@ExceptionHandler(Exception.class)
public Response exception(Exception ex, HttpServletRequest request) {
String requestId = (String) request.getAttribute(REQUEST_UNIQUE_ID_KEY);
// dinger异常通知
dingerSender.send(MessageSubType.TEXT, DingerRequest.request(ex.getMessage()));
return Response.failedMsg(ResponseEnum.SERVICE_ERROR, ex.getMessage());
}
}
扩展:自定义手动发送方式消息体格式
@Configuration
public class MyDingerConfiguration {
// 自定义text类型消息体,仅限手动发送功能,不适用于xml标签或注解统一管理消息体功能
@Bean
public CustomMessage textMessage() {
return (projectId, request) ->
MessageFormat.format(
"【Text通知】 {0}\n- 内容: {1}.",
projectId, request.getContent());
}
// 自定义markdown类型消息体
// @Bean
// public CustomMessage markDownMessage() {
// return (projectId, request) ->
// MessageFormat.format(
// "#### 【Markdown通知】 - 项目名称: {0}\n- 内容: {1}",
// projectId, request.getContent());
// }
}
方式2-Dinger接口方式
1、启动类新增@DingerScan注解
@SpringBootApplication
// 引入Dinger, basePackages填写dinger接口定义包路径
@DingerScan(basePackages = "com.jaemon.demo.dinger")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2、Dinger接口
package com.jaemon.demo.dinger;
public interface NoticeDinger {
// text文本类型
// @DingerText(value = "关键词: ${keyword}, 异常信息: ${message}", phones = {"13520210402"})
// markdown消息类型
@DingerMarkdown(
value = "#### 异常信息 @13520210402\n - 关键词: ${keyword}\n - 异常信息: ${message}",
title = "项目异常通知",
phones = {"13520210402"}
)
DingerResponse notice(@Parameter("keyword") String keyword, @Parameter("message") String message);
}
手机号请修改为实际需要艾特成员手机号
3、调整全局异常控制类
@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalController {
@Autowired
private NoticeDinger noticeDinger;
@ExceptionHandler(Exception.class)
public Response exception(Exception ex, HttpServletRequest request) {
String requestId = (String) request.getAttribute(REQUEST_UNIQUE_ID_KEY);
// dinger异常通知
noticeDinger.notice(requestId, ex.getMessage());
return Response.failedMsg(ResponseEnum.SERVICE_ERROR, ex.getMessage());
}
}
验证
模拟接口调用出现异常情况,并注意对应钉钉/企业微信群是否收到异常通知