一、机器人配置
1)新建群组
2)添加自定义机器人
二、代码开发
2.1 pom依赖
<!-- HTTP 客户端 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<!-- JSON 处理 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.48</version>
</dependency>
2.2 代码
package org.example;
import com.alibaba.fastjson2.JSON;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.util.EntityUtils;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
public class FeishuAlertUtil {
private static final String WEBHOOK_URL = "https://open.feishu.cn/open-apis/bot/v2/hook/xxx1";
private static final String SECRET = "xxx2"; // 机器人安全设置的密钥
public static void sendAlert(String message) throws Exception {
long timestamp = System.currentTimeMillis() / 1000;
String sign = generateSign(SECRET, timestamp);
// 构建消息体
Map<String, Object> content = new HashMap<>();
content.put("text", message);
Map<String, Object> payload = new HashMap<>();
payload.put("timestamp", timestamp);
payload.put("sign", sign);
payload.put("msg_type", "text");
payload.put("content", content);
// 发送请求
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(WEBHOOK_URL);
httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
httpPost.setEntity(new StringEntity(JSON.toJSONString(payload), StandardCharsets.UTF_8));
try (CloseableHttpResponse response = client.execute(httpPost)) {
System.out.println("飞书返回: " + EntityUtils.toString(response.getEntity()));
}
}
}
private static String generateSign(String secret, long timestamp) throws NoSuchAlgorithmException, InvalidKeyException {
//把timestamp+"\n"+密钥当做签名字符串
String stringToSign = timestamp + "\n" + secret;
//使用HmacSHA256算法计算签名
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] signData = mac.doFinal(new byte[]{});
return new String(Base64.encodeBase64(signData));
}
}
public class AlertDemo {
public static void main(String[] args) {
try {
FeishuAlertUtil.sendAlert("🚨 服务器CPU使用率超过95%!");
} catch (Exception e) {
System.err.println("告警发送失败: " + e.getMessage());
}
}
}
三、测试
运行AlertDemo类。
代码运行结果:
飞书返回: {"StatusCode":0,"StatusMessage":"success","code":0,"data":{},"msg":"success"}
Process finished with exit code 0
消息结果: