竹简文档
通知服务

Webhook 通知

WebhookNotify 通过 HTTP 回调实现消息推送能力

Webhook 通知

WebhookNotifyNotifyService 接口的 Webhook 通知实现,通过向指定 URL 发起 HTTP 回调完成消息推送。适用于对接企业通讯工具、CI/CD 流水线通知、第三方告警平台等场景。

类定义

WebhookNotify.java
package com.xlf.utility.notify;

// Webhook 通知实现,向目标 URL 发送 HTTP POST 请求
public class WebhookNotify implements NotifyService {

    @Override
    public NotifyResult send(NotifyMessage message) { ... }

    @Override
    public void sendAsync(NotifyMessage message) { ... }
}

使用方式

Webhook 通知中,to 字段用于指定回调 URL,content 字段为 HTTP 请求体内容。

基本发送

WebhookExample.java
import com.xlf.utility.notify.WebhookNotify;
import com.xlf.utility.notify.NotifyMessage;
import com.xlf.utility.notify.NotifyResult;
import com.xlf.utility.notify.NotifyType;

@Service
public class DeployNotifyService {
    private final NotifyService webhookNotify;

    public DeployNotifyService(WebhookNotify webhookNotify) {
        this.webhookNotify = webhookNotify;
    }

    public void notifyDeploySuccess(String service, String version) {
        // to 字段填写 Webhook 回调 URL
        NotifyMessage message = NotifyMessage.builder()
                .to("https://hooks.example.com/services/deploy")
                .subject("部署通知")
                .content("{\"service\":\"" + service + "\",\"version\":\"" + version + "\"}")
                .type(NotifyType.WEBHOOK)
                .priority(2)
                .build();

        NotifyResult result = webhookNotify.send(message);
        if (!result.isSuccess()) {
            log.warn("Webhook 推送失败: {}", result.getMessage());
        }
    }
}

携带模板变量

WebhookTemplateExample.java
import java.util.Map;

// 使用 variables 传递结构化数据
NotifyMessage message = NotifyMessage.builder()
        .to("https://hooks.example.com/services/alert")
        .subject("告警通知")
        .content("alert-template")
        .type(NotifyType.WEBHOOK)
        .variables(Map.of(
                "level", "WARNING",
                "service", "user-service",
                "message", "响应时间超过阈值"
        ))
        .build();

webhookNotify.sendAsync(message);

异步推送

对于非关键性通知,推荐使用异步发送避免阻塞主线程:

AsyncWebhookExample.java
// 异步发送,不阻塞当前线程
webhookNotify.sendAsync(message);

适用场景

场景说明
企业通讯集成对接钉钉、飞书、企业微信等 Incoming Webhook
CI/CD 流水线部署结果通知、构建状态回调
告警平台向 PagerDuty、Grafana OnCall 等平台推送告警
事件驱动业务事件触发第三方系统处理

错误处理

Webhook 发送失败时,NotifyResult 将包含 HTTP 响应状态或连接异常信息:

WebhookErrorExample.java
NotifyResult result = webhookNotify.send(message);
if (!result.isSuccess()) {
    // errorCode 可能包含 HTTP 状态码或异常类型
    log.error("Webhook 推送失败 [{}]: {}", result.getErrorCode(), result.getMessage());
}

下一步

On this page