SpringBoot怎么接入钉钉自定义机器人预警通知

发布时间:2022-07-15 14:00:27 作者:iii
来源:亿速云 阅读:519

SpringBoot怎么接入钉钉自定义机器人预警通知

1. 引言

在现代软件开发中,监控和预警系统是确保系统稳定性和可靠性的重要组成部分。随着微服务架构的普及,Spring Boot 成为了构建微服务的首选框架之一。而钉钉作为一款广泛使用的企业通讯工具,其自定义机器人功能可以方便地集成到各种系统中,用于发送预警通知。

本文将详细介绍如何在 Spring Boot 项目中接入钉钉自定义机器人,并通过代码示例展示如何实现预警通知功能。我们将从钉钉机器人的创建、Spring Boot 项目的配置、消息发送的实现等方面进行详细讲解。

2. 钉钉自定义机器人简介

钉钉自定义机器人是钉钉提供的一种消息推送服务,允许开发者通过 Webhook 将消息推送到钉钉群聊中。通过自定义机器人,可以实现自动化消息推送、预警通知、任务提醒等功能。

2.1 创建钉钉自定义机器人

  1. 登录钉钉开发者平台:首先,登录钉钉开发者平台(https://open.dingtalk.com/)。
  2. 创建机器人:在钉钉群聊中,点击右上角的“群设置” -> “智能群助手” -> “添加机器人” -> “自定义机器人”。
  3. 配置机器人:设置机器人名称、头像,并选择需要发送消息的群聊。
  4. 获取Webhook地址:创建完成后,系统会生成一个 Webhook 地址,该地址用于发送消息到钉钉群聊。

2.2 钉钉机器人消息格式

钉钉机器人支持多种消息格式,包括文本、链接、Markdown、ActionCard、FeedCard 等。本文将重点介绍如何使用文本和 Markdown 格式发送预警通知。

2.2.1 文本消息格式

{
    "msgtype": "text",
    "text": {
        "content": "预警通知:系统出现异常,请及时处理!"
    },
    "at": {
        "atMobiles": [
            "138xxxx8888"
        ],
        "isAtAll": false
    }
}

2.2.2 Markdown 消息格式

{
    "msgtype": "markdown",
    "markdown": {
        "title": "预警通知",
        "text": "#### 预警通知 \n > 系统出现异常,请及时处理! \n > ![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png) \n > ###### 10分钟前发布 [查看详情](https://www.dingtalk.com)"
    },
    "at": {
        "atMobiles": [
            "138xxxx8888"
        ],
        "isAtAll": false
    }
}

3. Spring Boot 项目配置

在 Spring Boot 项目中接入钉钉自定义机器人,首先需要配置相关的依赖和属性。

3.1 添加依赖

pom.xml 中添加以下依赖:

<dependencies>
    <!-- Spring Boot Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Spring Boot Actuator -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

    <!-- Spring Boot Configuration Processor -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>

    <!-- OkHttp -->
    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.9.1</version>
    </dependency>

    <!-- Lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

3.2 配置钉钉机器人Webhook地址

application.ymlapplication.properties 中配置钉钉机器人的 Webhook 地址:

dingtalk:
  robot:
    webhook: https://oapi.dingtalk.com/robot/send?access_token=your_access_token

3.3 创建配置类

创建一个配置类来加载钉钉机器人的配置:

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Data
@Configuration
@ConfigurationProperties(prefix = "dingtalk.robot")
public class DingTalkRobotConfig {
    private String webhook;
}

4. 实现钉钉机器人消息发送

4.1 创建消息发送工具类

创建一个工具类 DingTalkRobotUtil,用于发送消息到钉钉机器人:

import com.alibaba.fastjson.JSON;
import com.squareup.okhttp.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class DingTalkRobotUtil {

    @Autowired
    private DingTalkRobotConfig dingTalkRobotConfig;

    private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");

    public void sendTextMessage(String content, String[] atMobiles, boolean isAtAll) {
        TextMessage textMessage = new TextMessage(content, atMobiles, isAtAll);
        sendMessage(textMessage);
    }

    public void sendMarkdownMessage(String title, String text, String[] atMobiles, boolean isAtAll) {
        MarkdownMessage markdownMessage = new MarkdownMessage(title, text, atMobiles, isAtAll);
        sendMessage(markdownMessage);
    }

    private void sendMessage(Message message) {
        OkHttpClient client = new OkHttpClient();
        String json = JSON.toJSONString(message);
        RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, json);
        Request request = new Request.Builder()
                .url(dingTalkRobotConfig.getWebhook())
                .post(body)
                .build();

        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                log.info("消息发送成功:{}", json);
            } else {
                log.error("消息发送失败:{}", response.body().string());
            }
        } catch (IOException e) {
            log.error("消息发送异常:", e);
        }
    }

    @Data
    private static class TextMessage {
        private String msgtype = "text";
        private Text text;
        private At at;

        TextMessage(String content, String[] atMobiles, boolean isAtAll) {
            this.text = new Text(content);
            this.at = new At(atMobiles, isAtAll);
        }

        @Data
        private static class Text {
            private String content;

            Text(String content) {
                this.content = content;
            }
        }

        @Data
        private static class At {
            private String[] atMobiles;
            private boolean isAtAll;

            At(String[] atMobiles, boolean isAtAll) {
                this.atMobiles = atMobiles;
                this.isAtAll = isAtAll;
            }
        }
    }

    @Data
    private static class MarkdownMessage {
        private String msgtype = "markdown";
        private Markdown markdown;
        private At at;

        MarkdownMessage(String title, String text, String[] atMobiles, boolean isAtAll) {
            this.markdown = new Markdown(title, text);
            this.at = new At(atMobiles, isAtAll);
        }

        @Data
        private static class Markdown {
            private String title;
            private String text;

            Markdown(String title, String text) {
                this.title = title;
                this.text = text;
            }
        }

        @Data
        private static class At {
            private String[] atMobiles;
            private boolean isAtAll;

            At(String[] atMobiles, boolean isAtAll) {
                this.atMobiles = atMobiles;
                this.isAtAll = isAtAll;
            }
        }
    }
}

4.2 发送文本消息

在需要发送预警通知的地方,调用 DingTalkRobotUtilsendTextMessage 方法:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AlertService {

    @Autowired
    private DingTalkRobotUtil dingTalkRobotUtil;

    public void sendAlert(String message) {
        String[] atMobiles = {"138xxxx8888"};
        dingTalkRobotUtil.sendTextMessage(message, atMobiles, false);
    }
}

4.3 发送Markdown消息

如果需要发送更复杂的消息,可以使用 sendMarkdownMessage 方法:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AlertService {

    @Autowired
    private DingTalkRobotUtil dingTalkRobotUtil;

    public void sendAlert(String title, String message) {
        String[] atMobiles = {"138xxxx8888"};
        dingTalkRobotUtil.sendMarkdownMessage(title, message, atMobiles, false);
    }
}

5. 集成到Spring Boot Actuator

为了在系统出现异常时自动发送预警通知,可以将钉钉机器人集成到 Spring Boot Actuator 中。

5.1 配置Actuator

application.yml 中配置 Actuator:

management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: always

5.2 创建HealthIndicator

创建一个自定义的 HealthIndicator,用于监控系统健康状态,并在出现异常时发送预警通知:

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

@Component
public class CustomHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        // 模拟系统异常
        boolean systemError = true;

        if (systemError) {
            return Health.down().withDetail("Error Code", "500").build();
        } else {
            return Health.up().build();
        }
    }
}

5.3 监听Health事件

创建一个事件监听器,监听 Health 事件,并在系统健康状态变化时发送预警通知:

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthEndpoint;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class HealthEventListener {

    @Autowired
    private HealthEndpoint healthEndpoint;

    @Autowired
    private AlertService alertService;

    @EventListener
    public void onHealthEvent(Health health) {
        if (health.getStatus().equals(Health.down().build().getStatus())) {
            alertService.sendAlert("系统健康状态异常", "系统健康状态已变为 DOWN,请及时处理!");
        }
    }
}

6. 测试与验证

6.1 启动Spring Boot项目

启动 Spring Boot 项目,并访问 Actuator 的 /actuator/health 端点,查看系统健康状态。

6.2 模拟系统异常

CustomHealthIndicator 中模拟系统异常,观察钉钉群聊中是否收到预警通知。

6.3 验证消息发送

确保钉钉群聊中收到了正确的预警通知,并且消息格式符合预期。

7. 总结

通过本文的介绍,我们详细讲解了如何在 Spring Boot 项目中接入钉钉自定义机器人,并实现预警通知功能。通过集成 Spring Boot Actuator,我们可以实时监控系统健康状态,并在出现异常时自动发送预警通知,确保系统的稳定性和可靠性。

钉钉自定义机器人提供了丰富的消息格式和灵活的配置选项,可以满足不同场景下的需求。希望本文能够帮助读者更好地理解和应用钉钉自定义机器人,提升系统的监控和预警能力。

推荐阅读:
  1. Go语言实现钉钉发送通知
  2. zabbix - 对接钉钉机器人接口

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot

上一篇:npm run dev失败如何解决

下一篇:python中的字符转运算符、字符串处理方式是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》