1.因为springboot启动后会加载所用的配置文件,所以我们可以在main方法下写DingTalk的bean来注入DingTalk配置。
@ServletComponentScan public class Application { //DingTalk Bean变量 private static String DING_TALK_UTIL_BEAN = "dingtalkUtil"; public static void main(String[] args) { // new SpringApplicationBuilder(Application.class).initializers(new AqumonApplicationContextInitializer()).run(args); ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args); ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); //获取DingTalk Bean DingtalkUtil dingTalk = (DingtalkUtil) beanFactory.getBean(DING_TALK_UTIL_BEAN); //发送DingTalk通知 dingTalk.sendTextNotificationToAccountInfo("INFO:Account启动完成"); } }
2.DingTalk相关工具类及其方法:
@Data public class DingtalkUtil { Logger logger = LogManager.getLogger(DingtalkUtil.class); private URI WEBHOOK_URL_ACCOUNT; private URI WEBHOOK_URL_ACCOUNT_INFO; public DingtalkUtil(DingtalkConfig dingtalkConfig) { try { WEBHOOK_URL_ACCOUNT = new URI(dingtalkConfig.getAccountUrl()); WEBHOOK_URL_ACCOUNT_INFO = new URI(dingtalkConfig.getAccountInfoUrl()); } catch (URISyntaxException e) { logger.fatal("Failed to parse URI of reminder webhook, due to: " + e.getMessage()); } } /** * 发送文本提醒至Account警告群 * * @param msg 信息 */ public void sendTextNotificationToAccount(String msg) { sendTextNotification(msg, WEBHOOK_URL_ACCOUNT); } /** * 发送文本提醒至Account通知群 * */ public void sendTextNotificationToAccountInfo(String msg) { sendTextNotification(msg, WEBHOOK_URL_ACCOUNT_INFO); } /** * 发送文本提醒至任意机器人 * * @param msg 信息 * @param webhookUri 机器人的webhook地址,新的地址可在上面添加为常量 */ public void sendTextNotification(String msg, URI webhookUri) { RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>(buildJsonTextMessage(msg, false), headers); HttpEntity<String> response = restTemplate.postForEntity(webhookUri, entity, String.class); logger.info("Response: " + response.getBody()); } /** * 创建文本提醒Body * * @param msg * @param isAtAll * @return */ public String buildJsonTextMessage(String msg, boolean isAtAll) { StringBuilder sb = new StringBuilder(); String atAll = isAtAll ? "true" : "false"; sb.append("{ "msgtype": "text", "text": { "content": "" + msg + ""}, "isAtAll": " + atAll + "}"); return sb.toString(); }