4.2 dubbo provider启动之dubbo filter 详解

provider启动之前之Filter扩展。

filter的概念在很多框架框架都有涉及,实现的手法也是大同小异,链式调用,一环勾着一环,有点类似栈的思想,先进后出。

dubbo filter原生的filter挺多,足够常规使用,自实现后面再讲。现在由于在说provider的启动,所以先讲源码,把启动流程捋顺。

dubbo filter的初始化在于ProtocolFilterWrapper这个包装类里面的buildInvokerChain方法,这里依然使用SPI加载获取适合的filter,在filter的注解类似@Activate(group = Constants.PROVIDER, order = -110000),group表明是provider还是consumer,order为链式顺序,越小越先过滤。说回来,buildInvokerChain循环遍历filter并放入相应的invoker,形成单链表,层层调用。调用顺序:EchoFilter->ClassLoaderFilter->GenericFilter->ContextFilter->TraceFilter->TimeoutFilter->MonitorFilter->ExceptionFilter

简介:

EchoFilter:  回声测试用于检测服务是否可用,回声测试按照正常请求流程执行,能够测试整个调用是否通畅,可用于监控。

ClassLoaderFilter:切换线程上下文使用的classloader,用于SPI。

GenericFilter: 泛接口实现方式主要用于服务器端没有API接口及模型类元的情况,参数及返回值中的所有POJO均用Map表示,通常用于框架集成。

ContextFilter:处理请求的上下文信息。

TraceFilter:QOS服务中telnet相关调用。

TimeoutFilter:超时过滤器。

MonitorFilter: dubbo monitor监控相关。

ExceptionFilter:异常捕捉。

private static  Invoker buildInvokerChain(final Invoker invoker, String key, String group) {
    Invoker last = invoker;
    List filters = ExtensionLoader.getExtensionLoader(Filter.class).getActivateExtension(invoker.getUrl(), key, group);
    if (!filters.isEmpty()) {
        for (int i = filters.size() - 1; i >= 0; i--) {
            final Filter filter = filters.get(i);
            final Invoker next = last;
            last = new Invoker() {
                @Override
                public Class getInterface() {
                    return invoker.getInterface();
                }
                @Override
                public URL getUrl() {
                    return invoker.getUrl();
                }
                @Override
                public boolean isAvailable() {
                    return invoker.isAvailable();
                }
                @Override
                public Result invoke(Invocation invocation) throws RpcException {
                    Result result = filter.invoke(next, invocation);
                    if (result instanceof AsyncRpcResult) {
                        AsyncRpcResult asyncResult = (AsyncRpcResult) result;
                        asyncResult.thenApplyWithContext(r -> filter.onResponse(r, invoker, invocation));
                        return asyncResult;
                    } else {
                        return filter.onResponse(result, invoker, invocation);
                    }
                }
                @Override
                public void destroy() {
                    invoker.destroy();
                }
                @Override
                public String toString() {
                    return invoker.toString();
                }
            };
        }
    }
    return last;
}

EchoFilter:回声测试使用,发送任意字符串,返回该字符串,测试某个服务器是否开启。发什么返回什么。

@Override
public Result invoke(Invoker invoker, Invocation inv) throws RpcException {
    if (inv.getMethodName().equals(Constants.$ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) {
        return new RpcResult(inv.getArguments()[0]);
    }
    return invoker.invoke(inv);
}

classloaderFilter:类加载器切换

@Override
public Result invoke(Invoker invoker, Invocation invocation) throws RpcException {
    ClassLoader ocl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(invoker.getInterface().getClassLoader());
    try {
        return invoker.invoke(invocation);
    } finally {
        Thread.currentThread().setContextClassLoader(ocl);
    }
}

GenericFilter:传递方法名方法名直接调用,下例:

Object result = genericService.$invoke("sayHello", new String[] {"java.lang.String"}, new Object[] {"world"});

@Override
public Result invoke(Invoker invoker, Invocation inv) throws RpcException {
    if (inv.getMethodName().equals(Constants.$INVOKE)
            && inv.getArguments() != null
            && inv.getArguments().length == 3
            && !GenericService.class.isAssignableFrom(invoker.getInterface())) {
        String name = ((String) inv.getArguments()[0]).trim();
        String[] types = (String[]) inv.getArguments()[1];
        Object[] args = (Object[]) inv.getArguments()[2];
        try {
            Method method = ReflectUtils.findMethodByMethodSignature(invoker.getInterface(), name, types);
            Class[] params = method.getParameterTypes();
            if (args == null) {
                args = new Object[params.length];
            }
            String generic = inv.getAttachment(Constants.GENERIC_KEY);
            if (StringUtils.isBlank(generic)) {
                generic = RpcContext.getContext().getAttachment(Constants.GENERIC_KEY);
            }
            if (StringUtils.isEmpty(generic)
                    || ProtocolUtils.isDefaultGenericSerialization(generic)) {
                args = PojoUtils.realize(args, params, method.getGenericParameterTypes());
            } else if (ProtocolUtils.isJavaGenericSerialization(generic)) {
                for (int i = 0; i < args.length; i++) {
                    if (byte[].class == args[i].getClass()) {
                        try(UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream((byte[]) args[i])) {
                            args[i] = ExtensionLoader.getExtensionLoader(Serialization.class)
                                    .getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA)
                                    .deserialize(null, is).readObject();
                        } catch (Exception e) {
                            throw new RpcException("Deserialize argument [" + (i + 1) + "] failed.", e);
                        }
                    } else {
                        throw new RpcException(
                                "Generic serialization [" +
                                        Constants.GENERIC_SERIALIZATION_NATIVE_JAVA +
                                        "] only support message type " +
                                        byte[].class +
                                        " and your message type is " +
                                        args[i].getClass());
                    }
                }
            } else if (ProtocolUtils.isBeanGenericSerialization(generic)) {
                for (int i = 0; i < args.length; i++) {
                    if (args[i] instanceof JavaBeanDescriptor) {
                        args[i] = JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) args[i]);
                    } else {
                        throw new RpcException(
                                "Generic serialization [" +
                                        Constants.GENERIC_SERIALIZATION_BEAN +
                                        "] only support message type " +
                                        JavaBeanDescriptor.class.getName() +
                                        " and your message type is " +
                                        args[i].getClass().getName());
                    }
                }
            }
            Result result = invoker.invoke(new RpcInvocation(method, args, inv.getAttachments()));
            if (result.hasException()
                    && !(result.getException() instanceof GenericException)) {
                return new RpcResult(new GenericException(result.getException()));
            }
            if (ProtocolUtils.isJavaGenericSerialization(generic)) {
                try {
                    UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512);
                    ExtensionLoader.getExtensionLoader(Serialization.class)
                            .getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA)
                            .serialize(null, os).writeObject(result.getValue());
                    return new RpcResult(os.toByteArray());
                } catch (IOException e) {
                    throw new RpcException("Serialize result failed.", e);
                }
            } else if (ProtocolUtils.isBeanGenericSerialization(generic)) {
                return new RpcResult(JavaBeanSerializeUtil.serialize(result.getValue(), JavaBeanAccessor.METHOD));
            } else {
                return new RpcResult(PojoUtils.generalize(result.getValue()));
            }
        } catch (NoSuchMethodException e) {
            throw new RpcException(e.getMessage(), e);
        } catch (ClassNotFoundException e) {
            throw new RpcException(e.getMessage(), e);
        }
    }
    return invoker.invoke(inv);
}

ContextFilter:处理请求的上下文环境

@Override
    public Result invoke(Invoker invoker, Invocation invocation) throws RpcException {
        Map attachments = invocation.getAttachments();
        if (attachments != null) {
            attachments = new HashMap<>(attachments);
            attachments.remove(Constants.PATH_KEY);
            attachments.remove(Constants.INTERFACE_KEY);
            attachments.remove(Constants.GROUP_KEY);
            attachments.remove(Constants.VERSION_KEY);
            attachments.remove(Constants.DUBBO_VERSION_KEY);
            attachments.remove(Constants.TOKEN_KEY);
            attachments.remove(Constants.TIMEOUT_KEY);
            // Remove async property to avoid being passed to the following invoke chain.
            attachments.remove(Constants.ASYNC_KEY);
            attachments.remove(Constants.TAG_KEY);
            attachments.remove(Constants.FORCE_USE_TAG);
        }
        RpcContext.getContext()
                .setInvoker(invoker)
                .setInvocation(invocation)
//                .setAttachments(attachments)  // merged from dubbox
                .setLocalAddress(invoker.getUrl().getHost(),
                        invoker.getUrl().getPort());
        // merged from dubbox
        // we may already added some attachments into RpcContext before this filter (e.g. in rest protocol)
        if (attachments != null) {
            if (RpcContext.getContext().getAttachments() != null) {
                RpcContext.getContext().getAttachments().putAll(attachments);
            } else {
                RpcContext.getContext().setAttachments(attachments);
            }
        }
        if (invocation instanceof RpcInvocation) {
            ((RpcInvocation) invocation).setInvoker(invoker);
        }
        try {
            return invoker.invoke(invocation);
        } finally {
            // IMPORTANT! For async scenario, we must remove context from current thread, so we always create a new RpcContext for the next invoke for the same thread.
            RpcContext.removeContext();
            RpcContext.removeServerContext();
        }
    }


TraceFilter:QOS服务中telnet相关调用

    1. trace XxxService: 跟踪 1 次服务任意方法的调用情况
    2. trace XxxService 10: 跟踪 10 次服务任意方法的调用情况
    3. trace XxxService xxxMethod: 跟踪 1 次服务方法的调用情况
    4. trace XxxService xxxMethod 10: 跟踪 10 次服务方法的调用情况

@Override
public Result invoke(Invoker invoker, Invocation invocation) throws RpcException {
    long start = System.currentTimeMillis();
    Result result = invoker.invoke(invocation);
    long end = System.currentTimeMillis();
    if (tracers.size() > 0) {
        String key = invoker.getInterface().getName() + "." + invocation.getMethodName();
        Set channels = tracers.get(key);
        if (channels == null || channels.isEmpty()) {
            key = invoker.getInterface().getName();
            channels = tracers.get(key);
        }
        if (CollectionUtils.isNotEmpty(channels)) {
            for (Channel channel : new ArrayList<>(channels)) {
                if (channel.isConnected()) {
                    try {
                        int max = 1;
                        Integer m = (Integer) channel.getAttribute(TRACE_MAX);
                        if (m != null) {
                            max = m;
                        }
                        int count = 0;
                        AtomicInteger c = (AtomicInteger) channel.getAttribute(TRACE_COUNT);
                        if (c == null) {
                            c = new AtomicInteger();
                            channel.setAttribute(TRACE_COUNT, c);
                        }
                        count = c.getAndIncrement();
                        if (count < max) {
                            String prompt = channel.getUrl().getParameter(Constants.PROMPT_KEY, Constants.DEFAULT_PROMPT);
                            channel.send("\r\n" + RpcContext.getContext().getRemoteAddress() + " -> "
                                    + invoker.getInterface().getName()
                                    + "." + invocation.getMethodName()
                                    + "(" + JSON.toJSONString(invocation.getArguments()) + ")" + " -> " + JSON.toJSONString(result.getValue())
                                    + "\r\nelapsed: " + (end - start) + " ms."
                                    + "\r\n\r\n" + prompt);
                        }
                        if (count >= max - 1) {
                            channels.remove(channel);
                        }
                    } catch (Throwable e) {
                        channels.remove(channel);
                        logger.warn(e.getMessage(), e);
                    }
                } else {
                    channels.remove(channel);
                }
            }
        }
    }
    return result;
}

TimeoutFilter:超时过滤器,超时后输出警告日志

@Override
public Result invoke(Invoker invoker, Invocation invocation) throws RpcException {
    if (invocation.getAttachments() != null) {
        long start = System.currentTimeMillis();
        invocation.getAttachments().put(TIMEOUT_FILTER_START_TIME, String.valueOf(start));
    } else {
        if (invocation instanceof RpcInvocation) {
            RpcInvocation invc = (RpcInvocation) invocation;
            long start = System.currentTimeMillis();
            invc.setAttachment(TIMEOUT_FILTER_START_TIME, String.valueOf(start));
        }
    }
    return invoker.invoke(invocation);
}
MonitorFilter:MonitorFilter向DubboMonitor发送数据
@Override
public Result invoke(Invoker invoker, Invocation invocation) throws RpcException {
    if (invoker.getUrl().hasParameter(Constants.MONITOR_KEY)) {
        RpcContext context = RpcContext.getContext(); // provider must fetch context before invoke() gets called
        String remoteHost = context.getRemoteHost();
        long start = System.currentTimeMillis(); // record start timestamp
        getConcurrent(invoker, invocation).incrementAndGet(); // count up
        try {
            Result result = invoker.invoke(invocation); // proceed invocation chain
            collect(invoker, invocation, result, remoteHost, start, false);
            return result;
        } catch (RpcException e) {
            collect(invoker, invocation, null, remoteHost, start, true);
            throw e;
        } finally {
            getConcurrent(invoker, invocation).decrementAndGet(); // count down
        }
    } else {
        return invoker.invoke(invocation);
    }
}

ExceptionFilter:异常捕捉

@Override
public Result invoke(Invoker invoker, Invocation invocation) throws RpcException {
    try {
        return invoker.invoke(invocation);
    } catch (RuntimeException e) {
        logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost()
                + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName()
                + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e);
        throw e;
    }
}

filter是dubbo很重要的一环,对于拦截请求验证,处理入参,返回参数统一处理有很大的作用。

你可能感兴趣的:(dubbo源码解析)