Springboot-Admin集成钉钉机器人推送通知

公西凯捷
2023-12-01

Springboot-Admin集成钉钉机器人推送通知

参考文档

背景说明

之前尝试采用邮件推送通知,由于阿里云需要配置smtp邮件发送相关服务,才能发送邮件,另外邮件通知并不及时,平时办公也会使用钉钉,钉钉已经是工作中不可缺少的一部分,另外群机器人创建过程中也是必须要建立一个群,若是发现服务down机或下线可以及时通知到群中相关人。所以经过综合考虑,尝试集成钉钉机器人推送服务告警的通知。

钉钉机器人创建

参考 自定义机器人接入

代码集成

  1. 在pom.xml文件中添加代码
<!--仓库地址-->
<repositories>
        <repository>
            <id>sonatype-nexus-staging</id>
            <name>Sonatype Nexus Staging</name>
            <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
    
    
    <!--钉钉官方依赖-->
    <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>alibaba-dingtalk-service-sdk</artifactId>
            <version>1.0.1</version>
        </dependency>
  1. 创建java类,继承AbstractStatusChangeNotifier,类AbstractStatusChangeNotifier在Springboot Admin项目中,可参考MailNotifier类的实现
package cn.befory.config;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.taobao.api.ApiException;
import de.codecentric.boot.admin.server.domain.entities.Instance;
import de.codecentric.boot.admin.server.domain.entities.InstanceRepository;
import de.codecentric.boot.admin.server.domain.events.InstanceEvent;
import de.codecentric.boot.admin.server.domain.events.InstanceStatusChangedEvent;
import de.codecentric.boot.admin.server.notify.AbstractStatusChangeNotifier;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

/**
 * @author bys
 * @version 1.0
 * @since 2020/8/6
 */
@Configuration
@Slf4j
public class DingTalkNotifier extends AbstractStatusChangeNotifier {

    @Autowired
    private BeforyMonitorProperties beforyMonitorProperties;

    protected DingTalkNotifier(InstanceRepository repository) {
        super(repository);
    }

    @Override
    protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
        return Mono.fromRunnable(() -> {
            if (event instanceof InstanceStatusChangedEvent) {
                log.info("Instance {} ({}) is {}", instance.getRegistration().getName(), event.getInstance(),
                        ((InstanceStatusChangedEvent) event).getStatusInfo().getStatus());

                String status = ((InstanceStatusChangedEvent) event).getStatusInfo().getStatus();
                String messageText = String.format(beforyMonitorProperties.getDingtalkNotify().getTemplate(), instance.getRegistration().getName(),event.getInstance(), status,instance.getRegistration().getServiceUrl());
                this.sendTextMessage(messageText);
            } else {
                log.info("Instance {} ({}) {}", instance.getRegistration().getName(), event.getInstance(), event.getType());
            }
        });
    }


    /**
     * 发送消息
     * @param messageText
     */
    private void sendTextMessage(String messageText){
        DingTalkClient client = new DefaultDingTalkClient(beforyMonitorProperties.getDingtalkNotify().getWebhookToken());
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype(beforyMonitorProperties.getDingtalkNotify().getMsgType());
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(messageText);
        request.setText(text);
        try {
            client.execute(request);
        } catch (ApiException e) {
            log.info("[ERROR] sendMessage", e);
        }
    }
}
package cn.befory.config;

import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author bys
 * @version 1.0
 * @since 2020/8/7
 */
@Data
@Accessors(chain = true)
@Component
@ConfigurationProperties(prefix = "befory.monitor")
public class BeforyMonitorProperties {

    public static final String DEFAULT_TEMPLATE = "服务名:%s(%s) \n状态:%s \n服务IP:%s";

    public static final String DEFAULT_MSG_TYPE  = "text";

    private DingtalkNotify dingtalkNotify = new DingtalkNotify();


    @Data
    @Accessors(chain = true)
    public static class DingtalkNotify{
        /**
         * 创建机器人以后的token 注意保密,不能泄露
         */
        private String webhookToken;

        /**
         * String 标准模板 及格式化方式 eg:"服务名:%s(%s) \n状态:%s \n服务IP:%s";
         */
        private String template = DEFAULT_TEMPLATE;

        /**
         * 默认发送text类型数据,参考钉钉机器人文档 还支持link、markdown、actionCard、feedCard类型,
         * 详细开发思路参考钉钉开放文档
         */
        private String msgType = DEFAULT_MSG_TYPE;
    }
}
 类似资料: