失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > SpringBoot集成企业微信群机器人(运维报警)

SpringBoot集成企业微信群机器人(运维报警)

时间:2021-04-14 23:44:53

相关推荐

SpringBoot集成企业微信群机器人(运维报警)

之前有集成过钉钉群机器人🤖报警,这次主要是SpringBoot集成企业微信群机器人报警。

声明:

1.本篇文章不涉及任何业务数据

2.禁止转载!!!禁止转载!!!禁止转载!!!

相关文档:

企业微信群机器人配置说明

1. 配置

import lombok.Getter;import lombok.Setter;import org.springframework.boot.context.properties.ConfigurationProperties;import org.ponent;import java.util.List;/*** @descriptions: 配置参数* @author: xucl*/@Component@Getter@Setter@ConfigurationProperties(prefix = "notice")public class NoticeProperties {private String wechatKey;private List<String> phoneList;}

这个key的获取方式:群机器人配置说明

yaml文件配置数据:

notice:####### 企业微信群机器人keywechat-key: xxxxxxxxx-xxx-xxx-xxxx-xxxxxxxxxx####### 需要@的群成员手机号phone-list:

1.2 Http客户端配置

这里用的Forest ,感觉还挺强大灵活 官方文档,如果你喜欢使用httpClient或者okHttp建议你看看forest ;如果你更喜欢RestTemplate,那就使用RestTemplate。

POM依赖

<!-- 轻量级HTTP客户端框架 --><dependency><groupId>com.dtflys.forest</groupId><artifactId>forest-spring-boot-starter</artifactId><version>1.5.3</version></dependency>

yaml文件配置

日志打开关闭请参考自己的业务需要

## 轻量级HTTP客户端框架forestforest:# 配置底层API为 okhttp3backend: okhttp3# 连接池最大连接数,默认值为500max-connections: 1000# 每个路由的最大连接数,默认值为500max-route-connections: 500# 请求超时时间,单位为毫秒, 默认值为3000timeout: 3000# 连接超时时间,单位为毫秒, 默认值为2000connect-timeout: 3000# 请求失败后重试次数,默认为0次不重试retry-count: 1# 单向验证的HTTPS的默认SSL协议,默认为SSLv3ssl-protocol: SSLv3# 打开或关闭日志,默认为truelogEnabled: true# 打开/关闭Forest请求日志(默认为 true)log-request: true# 打开/关闭Forest响应状态日志(默认为 true)log-response-status: true# 打开/关闭Forest响应内容日志(默认为 false)log-response-content: true

发送Http

使用前请注意

在 Spring Boot 项目中调用接口#

只要在Spring Boot的配置类或者启动类上加上@ForestScan注解,并在basePackages属性里填上远程>接口的所在的包名,加入@ForestScan

src/main/java/MyApp.java

@SpringBootApplication@Configuration@ForestScan(basePackages = "com.yoursite.client")public class MyApp {...}

Forest 会扫描@ForestScan注解中basePackages属性指定的包下面所有的接口,然后会将符合条件的接口进行动态代理并注入到 Spring 的上下文中。

友情提示:

1.5.1以后版本可以跳过此步,不需要 @ForestScan 注解来指定扫描的包范围

发送请求的客户端

public interface NoticeClient {/*** 企业微信机器人 发送 https 请求** @param keyValue* @return*/@Post(url = "https://qyapi./cgi-bin/webhook/send?key={keyValue}",headers = {"Accept-Charset: utf-8","Content-Type: application/json"},dataType = "json")ForestResponse<JsonObject> weChatNotice(@Var("keyValue") String keyValue, @JSONBody Map<String, Object> body );}

RestTemplate方式

@Componentpublic class NoticeClient {@Autowiredprivate RestTemplate restTemplate;public static final String url = "https://qyapi./cgi-bin/webhook/send?key={weChatKey}";public ResponseEntity<JSONObject> weChatNotice(String weChatKey, Map<String, Object> body ){ResponseEntity<JSONObject> response = restTemplate.postForEntity(url, body, JSONObject.class,weChatKey);return response;}}

2.定义服务

2.1 接口

/*** @descriptions: 消息通知接口* @author: xucl*/public interface NoticeService {/*** 发送错误信息至群机器人* @param throwable* @param msg*/void sendError(Throwable throwable,String msg);/*** 发送文本信息至群机器人* @param msg*/void sendByMd(String msg);/*** 发送md至群机器人* @param msg 文本消息* @param isAtALL 是否@所有人 true是 false否*/void sendByText(String msg,boolean isAtALL);}

2.2 工具实现

注意:这里的包名(com.github)填自己项目内的包名

import com.dtflys.forest.http.ForestResponse;import com.google.gson.JsonObject;import lombok.extern.slf4j.Slf4j;import mons.collections4.CollectionUtils;import mons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;import java.io.ByteArrayOutputStream;import java.io.PrintStream;import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.regex.Matcher;import java.util.regex.Pattern;import java.util.stream.Collectors;/*** @descriptions: 通知实现* @author: xucl*/@Service@Slf4jpublic class NoticeServiceImpl implements NoticeService {@Value("${spring.application.name}")private String appName;@Value("${spring.profiles.active}")private String env;@Autowiredprivate NoticeClient noticeClient;@Autowiredprivate NoticeProperties noticeProperties;/*** 发送错误信息至群机器人** @param throwable* @param msg*/@Overridepublic void sendError(Throwable throwable, String msg) {String errorClassName = throwable.getClass().getSimpleName();if (StringUtils.isBlank(msg)){msg = throwable.getMessage() == null ? "出现null值" : throwable.getMessage();}ByteArrayOutputStream baos = new ByteArrayOutputStream();throwable.printStackTrace(new PrintStream(baos));String bodyStr = StringComUtils.limitStrNone(regexThrowableStr(baos.toString()),450);String md = getMdByTemplate(appName, env, errorClassName, msg, bodyStr);sendByMd(md);}/*** 发送文本信息至群机器人** @param msg*/@Overridepublic void sendByMd(String msg) {try {Map<String, Object> params = buildMdParams(msg);ForestResponse<JsonObject> response = noticeClient.weChatNotice(noticeProperties.getWechatKey(), params);log.debug("WeChatRobo-Send Error:{} Status:{}",response.isError(),response.getStatusCode());} catch (Exception e) {log.error("WeChatRobot-发送文本消息异常 body:{}",msg,e);}}/*** 发送md至群机器人** @param msg*/@Overridepublic void sendByText(String msg,boolean isAtALL) {try {Map<String, Object> params = buildTextParams(msg,noticeProperties.getPhoneList(),isAtALL);ForestResponse<JsonObject> response = noticeClient.weChatNotice(noticeProperties.getWechatKey(), params);log.debug("WeChatRobo-Send Error:{} Status:{}",response.isError(),response.getStatusCode());} catch (Exception e) {log.error("WeChatRobot-发送文本消息异常 body:{}",msg,e);}}/*** 构建发送文本消息格式的参数* @param phoneList @群用户* @param isAtALL 是否@所有人* @return*/private Map<String,Object> buildTextParams(String text, List<String> phoneList, boolean isAtALL){Map<String,Object> params = new HashMap<>();Map<String,Object> data = new HashMap<>();data.put("content",text);if (isAtALL){phoneList.add("@all");}if (CollectionUtils.isNotEmpty(phoneList)){data.put("mentioned_mobile_list", phoneList);}params.put("msgtype","text");params.put("text",data);return params;}/*** 构建发送markdown消息格式的参数** @param md* @return*/private Map<String,Object> buildMdParams(String md){Map<String,Object> params = new HashMap<>();Map<String,Object> data = new HashMap<>();data.put("content",md);params.put("msgtype","markdown");params.put("markdown",data);return params;}private String regexThrowableStr(String str){try {// 注意:这里的包名(com.github)填自己项目内的包名String pattern = "(com)(\\.)(github)(.{10,200})(\\))";Pattern r = pile(pattern);Matcher m=r.matcher(str);List<String> list = new ArrayList<>();while (m.find()) {list.add(m.group());}if (CollectionUtils.isEmpty(list)){return str;}String s = list.stream().collect(Collectors.joining("\n"));return s;} catch (Exception e) {return str;}}private String getMdByTemplate(String appName,String env,String errorClassName,String msg,String bodyStr){String titleTpl = "### 异常告警通知\n#### 应用:%s\n#### 环境:<font color=\"info\">%s</font>\n##### 异常:<font color=\"warning\">%s</font>\n";String bodyTpl = "\nMsg:%s\nDetail:\n>%s";String footerTpl = "\n<font color=\"comment\">%s</font>";String title = String.format(titleTpl, appName, env, errorClassName);String body = String.format(bodyTpl, msg,bodyStr);String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"));String footer = String.format(footerTpl, dateStr);return title.concat(body).concat(footer);}}

使用到的工具方法:

/*** 限制文本描述** @param content 内容或问题* @param charNumber 长度* @return*/public static String limitStrNone(String content ,int charNumber){if (StringUtils.isNotBlank(content)){if (content.length() > charNumber){String substring = content.substring(0, charNumber);return substring;}else {return content;}}return "";}

最终效果:

如果觉得《SpringBoot集成企业微信群机器人(运维报警)》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。