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

监听类

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 serviceNames = new ArrayList<>();

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

    private static Map 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 instances =  ((BddNamingEvent)event).getInstances();
                String serviceName = ((BddNamingEvent)event).getServiceName();
                cache.computeIfAbsent(serviceName, k -> instances.size());
                if(cache.get(serviceName) 

#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

你可能感兴趣的:(钉钉,java)