路由器

自定义路由策略

通过创建自定义路由器,您可以根据业务场景的特点实现特定的路由方法。

先决条件

选择两种部署和运行方法之一

基于 Kubernetes

  • 安装 Kubernetes 环境
  • 修改 Provider 中的配置文件以启用部署在 Kubernetes 中的 nacos 的地址
    # (The configuration remains the same as in the original documentation)
    
  • 修改 Consumer 中的配置文件以启用部署在 Kubernetes 中的 nacos 的地址
    # (The configuration remains the same as in the original documentation)
    
  • 部署 可扩展性路由器任务

使用本地 IDE

  • 部署 Nacos 版本 2.2.0
  • 修改 Provider 中的配置文件以启用本地 nacos 地址
    # (The configuration remains the same as in the original documentation)
    
  • 修改 Consumer 中的配置文件以启用本地 nacos 地址
    # (The configuration remains the same as in the original documentation)
    

任务详情

任务是坚持使用第一个开始提供服务的 Provider。如果该 Provider 离线,则选择一个新的 Provider。

实现方法

在 Consumer 中创建一个自定义路由器。在这个路由器中,保存第一次调用时使用的 Provider。对于后续调用,如果 Provider 列表包含第一次调用时使用的 Provider,则继续使用它;否则,选择一个新的 Provider。

代码结构

src
 |-main
    |-java
        |-org
            |-apache
                |-dubbo
                    |-samples
                        |-extensibility
                            |-router
                                |-consumer
                                    |-router
                                        |-StickFirstStateRouter.java (Implement StateRouter interface)
                                        |-StickFirstStateRouterFactory.java (Implement StateRouterFactory interface)
    |-resources
        |-META-INF
            |-application.properties (Dubbo Consumer configuration file)
            |-dubbo
                |-org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory (Plain text file)

代码详情

  • StickFirstStateRouter
package org.apache.dubbo.samples.extensibility.router.consumer.router;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
import org.apache.dubbo.rpc.cluster.router.state.BitList;

public class StickFirstStateRouter<T> extends AbstractStateRouter<T> implements ConfigurationListener {
    public StickFirstStateRouter(URL url) {
        super(url);
    }

    public static final String NAME = "STICK_FIRST_ROUTER";
    private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(StickFirstStateRouter.class);
    private volatile BitList<Invoker<T>> firstInvokers;

    @Override
    protected BitList<Invoker<T>> doRoute(BitList<Invoker<T>> invokers, URL url, Invocation invocation, boolean needToPrintMessage, Holder<RouterSnapshotNode<T>> routerSnapshotNodeHolder, Holder<String> messageHolder) throws RpcException {
        if (CollectionUtils.isEmpty(invokers)) {
            if (needToPrintMessage) {
                messageHolder.set("Directly Return. Reason: Invokers from previous router is empty.");
            }
            return invokers;
        }
        BitList<Invoker<T>> copy = invokers.clone();
        if (CollectionUtils.isEmpty(copy)) {
            this.firstInvokers = new BitList<>(BitList.emptyList());
            this.firstInvokers.add(copy.get(0));
        } else {
            this.firstInvokers = copy.and(invokers);
            if(CollectionUtils.isEmpty(this.firstInvokers)){
                this.firstInvokers.add(copy.get(0));
            }
        }
        return this.firstInvokers;
    }

    @Override
    public void process(ConfigChangedEvent event) {
        if (logger.isDebugEnabled()) {
            logger.debug("Notification of tag rule, change type is: " + event.getChangeType() + ", raw rule is:\n " +
                    event.getContent());
        }
        // Reset
        if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
            this.firstInvokers = null;
        }
    }

    @Override
    public void stop() {
        super.stop();
        this.firstInvokers = null;
    }
}
  • StickFirstStateRouterFactory
package org.apache.dubbo.samples.extensibility.router.consumer.router;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;

public class StickFirstStateRouterFactory implements StateRouterFactory {
    @Override
    public <T> StateRouter<T> getRouter(Class<T> interfaceClass, URL url) {
        return new StickFirstStateRouter<>(url);
    }
}

SPI 配置

resources/META-INF/dubbo/org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory 文件中添加以下配置

stickfirst=org.apache.dubbo.samples.extensibility.router.consumer.router.StickFirstStateRouterFactory

配置文件

resources/application.properties 文件中添加以下配置

# Configure custom router
dubbo.consumer.router=stickfirst

执行结果

使用 使用本地 IDE 方法运行任务,结果如下

dubbo-samples-extensibility-router-output.png

总而言之,Dubbo 的可扩展性允许您创建自定义路由器,提供了一种根据您的业务需求自定义路由逻辑的方法。本教程演示了如何创建“坚持使用第一个 Provider”的路由策略,这对于优化网络流量和减少延迟很有用。


上次修改时间:2023 年 11 月 1 日:Translate extension related docs (#2844) (e603103c03a)