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

该文章描述了一个SpringBoot主启动类,它依赖于`apiRegistrationChecker`进行初始化。`ApiRegistrationChecker`是一个配置类,用于检查Dubbo服务在ZooKeeper中的注册状态。通过读取XML配置文件,连接ZooKeeper,检查每个服务接口是否已注册。如果服务未注册,会进行重试机制,等待服务提供者启动完成。同时,文章还展示了一个`ApiBeanDefinitionRegistryPostProcessor`,用于在Spring容器启动时注册`apiRegistrationChecker`bean。

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

主启动类配置

//添加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());
    }
}
### 关于 Dubbo 2.7.22 中 MigrationRuleListener 的使用方法 在 Dubbo 2.7.22 版本中,`MigrationRuleListener` 是用于监听迁移规则变化的重要组件。当服务提供者或消费者配置发生变更时,该监听器能够及时响应并执行相应的操作。 #### 创建自定义 `MigrationRuleListener` 为了实现特定业务逻辑下的迁移规则监听功能,可以创建一个继承自 `com.alibaba.dubbo.config.listener.MigrationRuleListenerAdapter` 类的新类,并重写其中的方法来处理事件通知: ```java public class CustomMigrationRuleListener extends MigrationRuleListenerAdapter { @Override public void notify(MigrationRule rule, NotifyType type) { super.notify(rule, type); System.out.println("Received notification for migration rule " + rule.getService() + ", action=" + (type == null ? "" : type.name())); } } ``` 此代码片段展示了如何通过扩展默认适配器来自定义行为[^1]。 #### 注册 `MigrationRuleListener` 要使上述自定义监听器生效,还需要将其注册到 Dubbo 系统中。这可以通过 XML 配置文件完成,也可以利用 Java API 动态添加。以下是基于 Spring Boot 应用程序的一个例子: ```xml <dubbo:listener id="customMigrationRuleListener" ref="customMigrationRuleListenerBean"/> <bean id="customMigrationRuleListenerBean" class="org.example.CustomMigrationRuleListener"/> ``` 这段 XML 定义了一个名为 `customMigrationRuleListener` 的监听器实例,并指定了其对应的 Bean 实现类。 对于采用纯编码方式的应用,则可以直接注入依赖并将其实例化为监听器对象: ```java @Autowired private ApplicationContext applicationContext; @Bean public Listener customMigrationRuleListener(){ return new CustomMigrationRuleListener(); } // 在适当位置调用如下方法以启动监听过程 applicationContext.getAutowireCapableBeanFactory().initializeBean(customMigrationRuleListener(),null); ``` 以上示例说明了如何将自定义的 `CustomMigrationRuleListener` 添加至容器内以便被自动发现和初始化。 #### 解决常见问题方案 如果遇到与 `MigrationRuleListener` 相关的问题,建议按照以下思路排查原因: - **确认版本兼容性**:确保使用的 Dubbo 及其他相关库均为最新稳定版,避免因版本差异引起的功能缺失或异常。 - **检查日志输出**:查看应用程序的日志记录,特别是 WARN 和 ERROR 级别的消息,寻找可能存在的错误提示信息。 - **验证配置项准确性**:仔细核对所有涉及的服务治理参数设置是否正确无误,包括但不限于协议类型、地址映射关系等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值