com.alibaba.dubbo 启动监听某些必要的提供者 api

主启动类配置

//添加DependsOn注解,启动时去检测
@DependsOn("apiRegistrationChecker")
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(Application.class);
        //通过 SpringApplication 注册 ApplicationContextInitializer
        application.addInitializers(new ApiBeanDefinitionRegistryPostProcessor());
        //运行 headless 服务器,来进行简单的图像处理
        application.setHeadless(true);
        application.run(args);
    }
    
}

核心检测配置

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.rpc.service.GenericService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

@Slf4j
@Configuration
public class ApiRegistrationChecker implements InitializingBean {

    private final ResourceLoader resourceLoader;

    @Value("${zookeeper.address}")
    private String registryAddress;
    @Value("${spring.application.name:mnis}")
    private String applicationName;

    public ApiRegistrationChecker(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void afterPropertiesSet() {
        ZooKeeper zooKeeper = null;
        try {
            Resource resource = resourceLoader.getResource("classpath:dubbo/dubbo-config.xml");
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
            factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
            DocumentBuilder documentBuilder = factory.newDocumentBuilder();
            Document document = documentBuilder.parse(resource.getInputStream());
            NodeList nodeList = document.getElementsByTagName("dubbo:reference");
            // 获取 ZooKeeper 客户端连接
            String zkAddress = registryAddress.replace("zookeeper://", "");
            zooKeeper = createZooKeeperClient(zkAddress); // 替换为您的 ZooKeeper 服务器地址
            List<String> retryInterFaceName = new ArrayList<>();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Element element = (Element) nodeList.item(i);
                String check = element.getAttribute("check");
                if (StringUtils.isEmpty(check)) {
                    check = "true";
                }
                String interfaceName = element.getAttribute("interface");

                // 在这里执行检测注册状态的逻辑
                if (Boolean.parseBoolean(check) && !checkStatus(interfaceName, zooKeeper)) {
                    retryInterFaceName.add(interfaceName);
                }
            }
            //重试机制
            retry(retryInterFaceName, zooKeeper);
        } catch (Exception e) {
            log.error("校验注册状态失败:", e);
        } finally {
            if (Objects.nonNull(zooKeeper)) {
                try {
                    zooKeeper.close();
                } catch (Exception exception) {
                    Thread.currentThread().interrupt();
                    log.error("关闭zookeeper连接失败:", exception);
                }
            }
        }
    }

    private void retry(List<String> retryInterFaceName, ZooKeeper zooKeeper) {
        while (CollectionUtils.isNotEmpty(retryInterFaceName)) {
            try {
                Thread.sleep(1000 * 10L);
                log.error("休眠10s,等待dubbo提供者启动完成...,");
            } catch (Exception exception) {
                Thread.currentThread().interrupt();
                log.error("休眠10s,等待dubbo提供者启动完成...,");
            }
            List<String> successCodes = new ArrayList<>();
            for (String interfaceName : retryInterFaceName) {
                if (checkStatus(interfaceName, zooKeeper)) {
                    successCodes.add(interfaceName);
                }
            }
            retryInterFaceName.removeAll(successCodes);
        }
    }

    private boolean checkStatus(String interfaceName, ZooKeeper zooKeeper) {
        boolean flag = false;
        try {
            ApplicationConfig applicationConfig = new ApplicationConfig();
            applicationConfig.setName(applicationName);
            RegistryConfig registryConfig = new RegistryConfig();
            registryConfig.setAddress(registryAddress); // 替换为你的注册中心地址
            ReferenceConfig<GenericService> referenceConfig = new ReferenceConfig<>();
            referenceConfig.setApplication(applicationConfig);
            referenceConfig.setRegistry(registryConfig);
            referenceConfig.setInterface(interfaceName);
            referenceConfig.setGeneric(true);
            GenericService genericService = referenceConfig.get();
            if (Objects.isNull(genericService)) {
                log.error("{}---------->未注册到zookeeper", interfaceName);
                return false;
            }
            // 要检查的 Dubbo 服务信息
            String servicePath = "/dubbo/" + interfaceName + "/providers";
            // 检查服务的注册状态
            Stat stat = zooKeeper.exists(servicePath, false);
            if (Objects.nonNull(stat)) {
                flag = true;
                log.info("{}---------->已注册成功", interfaceName);
            } else {
                log.error("{}---------->未注册到zookeeper", interfaceName);
            }
        } catch (Exception exception) {
            Thread.currentThread().interrupt();
            log.error("zookeeper检查 {} api 注册状态失败...", interfaceName);
        }
        return flag;
    }

    //创建zookeeper客户端连接
    private static ZooKeeper createZooKeeperClient(String zkConnectString) throws IOException {
        return new ZooKeeper(zkConnectString, 5000, event -> {
        });
    }
}
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.PriorityOrdered;

/**
 * @ClassName: MyBeanDefinitionRegistryPostProcessor
 * @Description:
 * @Author: hongjun.chen@lachesis-mh.com
 * @Date: 2023/7/25 21:41
 * @Version: 1.0
 */
@Slf4j
public class ApiBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor,
    PriorityOrdered,
    ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        // 手动注册一个 BeanDefinition
        registry.registerBeanDefinition("apiRegistrationChecker", new RootBeanDefinition(ApiRegistrationChecker.class));
        BeanDefinition apiRegistrationChecker = registry.getBeanDefinition("apiRegistrationChecker");
        apiRegistrationChecker.setLazyInit(false);
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        // 在这里添加你的特定bean定义
        /*String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
        for (int i = 0; i < beanDefinitionNames.length; i++) {
            log.info("=================={} {} ", i, beanDefinitionNames[i]);
        }*/
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        applicationContext.addBeanFactoryPostProcessor(new ApiBeanDefinitionRegistryPostProcessor());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值