监听Nacos服务上线下,并发送通知到钉钉

本文介绍了如何通过Java实现对Nacos服务上下线的监听,并结合BddNamingEvent、BddInstancesChangeNotifier等类,以及BddServiceInfo和BddInstancesChangeEvent事件来触发钉钉的通知服务,确保及时获取服务状态变化信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

监听类

package com.bdd.iot.config.nacos;

import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.bdd.iot.config.my.MyDefinedConfig;
import com.bdd.iot.service.DingTalkService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 
 * @date 2022-08-19 10:26
 */

@Log4j2
@Component
public class ServiceNacosListner  {

    @Autowired
    private MyDefinedConfig myDefinedConfig;

    private static final String DING_DING_TOKEN = "钉钉token";

    private static final String DING_DING_SECRET = "钉钉secret";

    public static List<String> serviceNames = new ArrayList<>();

    static {
        serviceNames.add("bms");
        serviceNames.add("gateway");
    }

    private static Map<String, Integer> cache = new ConcurrentHashMap<>();


    @PostConstruct
    public void init() throws Exception {
        Properties properties = System.getProperties();
        properties.setProperty("serverAddr", myDefinedConfig.getDiscoveryUrl());
        properties.setProperty("namespace", "public");
        properties.setProperty(PropertyKeyConst.USERNAME, myDefinedConfig.getNacosUsername());
        properties.setProperty(PropertyKeyConst.PASSWORD, myDefinedConfig.getNacosPassword());
        NamingService naming = NamingFactory.createNamingService(properties);
        log.info("当前监听nacos地址:{}",myDefinedConfig.getDiscoveryUrl());
        for(String service : serviceNames) {
            naming.subscribe(service, event -> {
                log.info("触发监听");
                List<Instance> instances =  ((BddNamingEvent)event).getInstances();
                String serviceName = ((BddNamingEvent)event).getServiceName();
                cache.computeIfAbsent(serviceName, k -> instances.size());
                if(cache.get(serviceName) <instances.size()){
                    cache.put(serviceName, instances.size());
                }
                if(instances.size() <cache.get(serviceName)) {
                    log.info("============服务下线"+ serviceName);
                    cache.put(serviceName, instances.size());
                    try {
                        sendDingDingMessage(2,(BddNamingEvent)event);
                    } catch (InterruptedException | IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    log.info("============服务上线"+ serviceName+",当前节点数量:"+instances.size());
                    try {
                        sendDingDingMessage(1,(BddNamingEvent)event);
                    } catch (InterruptedException | IOException e) {
                        e.printStackTrace();
                    }

                }
            });
        }
    }

    public void sendDingDingMessage(Integer type,BddNamingEvent event) throws InterruptedException, IOException {
        String[] serviceInformation = event.getServiceName().split("@");
        DingTalkService.sendDingDing(
                "服 务 名 称:"
                        +serviceInformation[2]
                        +"\n分 组 名 称:"
                        +serviceInformation[0]
                        +"\nI               P:"
                        +event.getIp()
                        +"\n端           口:"
                        +event.getPort()
                        +"\n状           态:"+ (type == 1 ? "上线[对勾]" :"下线[打叉]")
                        +"\n当前节点数:"+event.getInstances().size()
                        +"\nnacos 地址:"+ (myDefinedConfig.getActive().equals("prod") ? "127.0.0.1:8848" : myDefinedConfig.getDiscoveryUrl()),
                DING_DING_TOKEN,
                DING_DING_SECRET);
        if(type != 1 && serviceInformation[2].equals("bdd-gateway") && "test".equalsIgnoreCase(myDefinedConfig.getActive())){
            Thread.sleep(5000);
            Runtime.getRuntime().exec("sh /root/boot.sh bdd-gateway 89");

        }
    }

}

#BddNamingEvent类

 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * W
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JinMeiLe

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值