思路 目前java应用都是大多数使用logback,可以自定logback appender来对日志进行拦截,既然是报警只拦截ERROR即可,具体怎么处理是接入钉钉,还是企业微信,或者邮件根据具体需要处理即可。
@Slf4j
public class DingUtils {
public static Map<Integer, KV> map = new HashMap<>();
public static RateLimiter rateLimiter = null;
public static AtomicInteger atomicInteger = new AtomicInteger(0);
@Data
public static class KV{
private String k;
private String v;
}
/**
* 加载类的时候初始化
* */
static {
try {
ClassPathResource classPathResource = new ClassPathResource("prop/dingding.properties");
InputStream in = classPathResource.getInputStream();
// File file = new File(url.getPath(), "/prop/dingding.properties");
// FileInputStream in = new FileInputStream(file);
Properties properties = new Properties();
properties.load(in);
Enumeration<Object> keys = properties.keys();
int count = 0;
while (keys.hasMoreElements()){
String k = keys.nextElement().toString();
KV kv = new KV();
String value = properties.getProperty(k);
String[] split = value.split("&");
kv.setK(split[0]);
kv.setV(split[1]);
map.put(count++,kv);
}
BigDecimal a = new BigDecimal(map.size() * 20);
BigDecimal v = a.divide(new BigDecimal(60),2,BigDecimal.ROUND_DOWN);
rateLimiter = RateLimiter.create(v.doubleValue());
System.err.println(rateLimiter);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取对应机器人
* */
public static KV getKV(){
//轮询每个机器人即可 (最简单了)
int idx = atomicInteger.getAndIncrement() % map.size();
return map.get(idx);
}
/**
* 给钉钉群发送消息方法
*
* @param content 消息内容
* @return
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
* @throws InvalidKeyException
*/
public static String sendMsg(String content) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
try {
rateLimiter.acquire();
content = "监控报警 ====>" + content;
//群机器人复制到的秘钥secret
KV kv = getKV();
String secret = kv.getV();
//获取系统时间戳
long timestamp = Instant.now().toEpochMilli();
//拼接
String stringToSign = timestamp + "\n" + secret;
//使用HmacSHA256算法计算签名
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
//进行Base64 encode 得到最后的sign,可以拼接进url里
String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
//钉钉机器人地址(配置机器人的webhook)
String dingUrl = kv.getK()+"×tamp=" + timestamp + "&sign=" + sign;
Map<String,String> map = new HashMap<>();
map.put("msgtype","text");
Map<String,String> body = new HashMap<>();
body.put("content",content);
map.put("text",JSON.toJSONString(body));
String result = HttpUtils.post(dingUrl, map, null);
return result;
} catch (Exception e) {
log.info("钉钉推送消息出现异常 ", e);
return null;
}
}
}