钉钉群消息提醒工具类
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class DingAlertUtil {
public static final String WEBHOOK = "";
public static final String SECRET = "";
public static void alertDingMsg(String msg) {
sendText(WEBHOOK, SECRET, msg);
}
public static HttpResponse sendText(String webhook, String secret, String content) {
//get url
String url = webhook;
if (StringUtils.isNotBlank(secret)) {
long timestamp = System.currentTimeMillis();
url = webhook + String.format("×tamp=%s&sign=%s", timestamp, getSign(timestamp, secret));
}
//get body
Map<String, Object> reqMap = Maps.newHashMap();
reqMap.put("msgtype", "text");
Map<String, String> contentMap = Maps.newHashMap();
contentMap.put("content", content);
reqMap.put("text", contentMap);
//
return HttpRequest.post(url).body(JSON.toJSONString(reqMap)).execute();
}
private static String getSign(Long timestamp, String secret) {
try {
String stringToSign = timestamp + "\n" + secret;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
return URLEncoder.encode(cn.hutool.core.codec.Base64.encode(signData), "UTF-8");
} catch (Exception ex) {
return null;
}
}
}
业务接入钉钉群消息提醒
try {
long startTimestamp = System.currentTimeMillis();
log.info("[某某业务]开始");
doSysInvoiceNoteRefresh();
log.info(String.format("[某某业务]结束, 耗时%dms", System.currentTimeMillis() - startTimestamp));
} catch (Exception e) {
//dingAlert
if (StringUtils.isEmpty(dingAlertEnv)) {
dingAlertEnv = Strings.EMPTY;
}
log.info("[某某业务], dingAlertEnv:{}", dingAlertEnv);
DingAlertUtil.alertDingMsg(String.format("[%s][%s][%s][%s]%s", dingAlertEnv, "某某业务", MDC.get("kctrace"), e.getClass().getSimpleName(), e.getMessage()));
//
log.error(String.format("[某某业务]异常, 异常信息: %s", e.getMessage()), e);
e.printStackTrace();
}
借鉴自