dubbo源码解析之路由规则

1、路由规则的更新

路由配置信息有变动,通知RegistryDirectory#notify(List urls),下面以Zookeeper为例讲解。

public synchronized void notify(List<URL> urls) {
    
    
    ...
    List<URL> routerUrls = new ArrayList<URL>();
    ...
    for (URL url : urls) {
    
    
        String protocol = url.getProtocol();
        String category = url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY);
        if (Constants.ROUTERS_CATEGORY.equals(category)
                || Constants.ROUTE_PROTOCOL.equals(protocol)) {
    
    
            routerUrls.add(url);
        }
        ...
    }
    ...
    // routers
    if (routerUrls != null && !routerUrls.isEmpty()) {
    
    
        // 获取路由
        // 下面详细讲解
        List<Router> routers = toRouters(routerUrls);
        if (routers != null) {
    
     // null - do nothing
            // 设置路由
            setRouters(routers);
        }
    }
    ...
}

取出有变动的url -> 获取路由 -> 设置路由。下面详细讲解一下“获取路由”的过程。

// RegistryDirectory#toRouters(List<URL>)
private List<Router> toRouters(List<URL> urls) {
    
    
    List<Router> routers = new ArrayList<Router>();
    if (urls == null || urls.isEmpty()) {
    
    
        return routers;
    }
    if (urls != null && !urls.isEmpty()) {
    
    
        for (URL url : urls) {
    
    
            if (Constants.EMPTY_PROTOCOL.equals(url.getProtocol())) {
    
    
                continue;
            }
            String routerType = url.getParameter(Constants.ROUTER_KEY);
            if (routerType != null && routerType.length() > 0) {
    
    
                url = url.setProtocol(routerType);
            }
            try {
    
    
                // RouterFactory是一个@SPI类,getRouter(URL)方法是@Adaptive("protocol")修饰的,所以通过url.protocol决定实现类
                Router router = routerFactory.getRouter(url);
                if (!routers.contains(router))
                    routers.add(router);
            } catch (Throwable t) {
    
    
                logger.error("convert router url to router error, url: " + url, t);
            }
        }
    }
    return routers;
}
2、路由规则的使用

在获取Invokers列表时,首先会通过Directory选出当前可用的Invokers列表,然后通过Router接口的route(List<Invoker>, URL, Invocation)过滤不符合路由规则的Invokers。下面看看具体实现。

2.1 使用路由规则对Invokers的过滤
// AbstractDirectory#list(Invocation invocation)
public List<Invoker<T>> list(Invocation invocation) throws RpcException {
    
    
    ...
    // 通过Directory选出当前可用的Invokers列表
    List<Invoker<T>> invokers = doList(invocation);
    // 路由过滤
    List<Router> localRouters = this.routers; // local reference
    if (localRouters != null && !localRouters.isEmpty()) {
    
    
        for (Router router : localRouters) {
    
    
            try {
    
    
                if (router.getUrl() == null || router.getUrl().getParameter(Constants.RUNTIME_KEY, false)) {
    
    
                    invokers = router.route(invokers, getConsumerUrl(), invocation);
                }
            } catch (Throwable t) {
    
    
                logger.error("Failed to execute router: " + getUrl() + ", cause: " + t.getMessage(), t);
            }
        }
    }
    return invokers;
}
2.2 第一种实现路由过滤:ConditionRouter#route(List<Invoker>, URL, Invocation)
// ConditionRouter#route(List<Invoker<T>>, URL, Invocation)
public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation)
        throws RpcException {
    
    
    if (invokers == null || invokers.isEmpty()) {
    
    
        return invokers;
    }
    try {
    
    
        // 匹配规则:host = 10.99.1.109 =>  host = 10.20.3.3,就是消费者ip为10.99.1.109的,转向提供者ip为10.20.3.3的服务器
        // when: => 的前半部分,也就是 host = 10.99.1.109
        if (!matchWhen(url, invocation)) {
    
    
            return invokers;
        }
        List<Invoker<T>> result = new ArrayList<Invoker<T>>();
        if (thenCondition == null) {
    
    
            logger.warn("The current consumer in the service blacklist. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey());
            return result;
        }
        for (Invoker<T> invoker : invokers) {
    
    
            // 匹配then条件
            // then: => 的后半部分,也就是 host = 10.20.3.3
            if (matchThen(invoker.getUrl(), url)) {
    
    
                result.add(invoker);
            }
        }
        if (!result.isEmpty()) {
    
    
            return result;
        } else if (force) {
    
    
            logger.warn("The route result is empty and force execute. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey() + ", router: " + url.getParameterAndDecoded(Constants.RULE_KEY));
            return result;
        }
    } catch (Throwable t) {
    
    
        logger.error("Failed to execute condition router rule: " + getUrl() + ", invokers: " + invokers + ", cause: " + t.getMessage(), t);
    }
    return invokers;
}

ConditionRouter是按配置的条件进行过滤,下面是ScriptRouter按脚本进行过滤的方式。

2.2 第二种实现路由过滤:ScriptRouter#route(List<Invoker>, URL, Invocation)
// ScriptRouter#route(List<Invoker<T>>, URL, Invocation)
public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
    
    
    try {
    
    
        List<Invoker<T>> invokersCopy = new ArrayList<Invoker<T>>(invokers);
        // 脚本引擎engine = new ScriptEngineManager()
        Compilable compilable = (Compilable) engine;
        Bindings bindings = engine.createBindings();
        bindings.put("invokers", invokersCopy);
        bindings.put("invocation", invocation);
        bindings.put("context", RpcContext.getContext());
        // 编译规则
        // rule是在FileRouterFactory#getRouter()中赋值的
        CompiledScript function = compilable.compile(rule);
        Object obj = function.eval(bindings);
        if (obj instanceof Invoker[]) {
    
    
            invokersCopy = Arrays.asList((Invoker<T>[]) obj);
        } else if (obj instanceof Object[]) {
    
    
            invokersCopy = new ArrayList<Invoker<T>>();
            for (Object inv : (Object[]) obj) {
    
    
                invokersCopy.add((Invoker<T>) inv);
            }
        } else {
    
    
            invokersCopy = (List<Invoker<T>>) obj;
        }
        return invokersCopy;
    } catch (ScriptException e) {
    
    
        //fail then ignore rule .invokers.
        logger.error("route error , rule has been ignored. rule: " + rule + ", method:" + invocation.getMethodName() + ", url: " + RpcContext.getContext().getUrl(), e);
        return invokers;
    }
}

FileRouterFactory通过File读取规则脚本,新建一个脚本引擎ScriptEngineManager读取上面的脚本,获取Invokers列表。下面详细讲解一下FileRouterFactory读取脚本的过程。

// FileRouterFactory#getRouter(URL url)
public Router getRouter(URL url) {
    
    
    try {
    
    
        // Transform File URL into Script Route URL, and Load
        // file:///d:/path/to/route.js?router=script ==> script:///d:/path/to/route.js?type=js&rule=<file-content>
        String protocol = url.getParameter(Constants.ROUTER_KEY, ScriptRouterFactory.NAME); // Replace original protocol (maybe 'file') with 'script'
        String type = null; // Use file suffix to config script type, e.g., js, groovy ...
        // 获取url的path属性
        // TODO 这个path是怎么赋值的
        String path = url.getPath();
        if (path != null) {
    
    
            int i = path.lastIndexOf('.');
            if (i > 0) {
    
    
                type = path.substring(i + 1);
            }
        }
        // 获取过滤规则
        String rule = IOUtils.read(new FileReader(new File(url.getAbsolutePath())));

        boolean runtime = url.getParameter(Constants.RUNTIME_KEY, false);
        // 设置rule属性到url对象中
        URL script = url.setProtocol(protocol).addParameter(Constants.TYPE_KEY, type).addParameter(Constants.RUNTIME_KEY, runtime).addParameterAndEncoded(Constants.RULE_KEY, rule);
        // 获取ScriptRouter的实例
        return routerFactory.getRouter(script);
    } catch (IOException e) {
    
    
        throw new IllegalStateException(e.getMessage(), e);
    }
}

猜你喜欢

转载自blog.csdn.net/fomeiherz/article/details/101031435
今日推荐