转载

聊聊dubbo的TimeoutFilter

本文主要研究一下dubbo的TimeoutFilter

ListenableFilter

dubbo-2.7.2/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ListenableFilter.java

public abstract class ListenableFilter implements Filter {

    protected Listener listener = null;

    public Listener listener() {
        return listener;
    }
}
  • ListenableFilter声明实现Filter接口,它主要定义了listener()方法

TimeoutFilter

dubbo-2.7.2/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java

@Activate(group = CommonConstants.PROVIDER)
public class TimeoutFilter extends ListenableFilter {

    private static final Logger logger = LoggerFactory.getLogger(TimeoutFilter.class);

    private static final String TIMEOUT_FILTER_START_TIME = "timeout_filter_start_time";

    public TimeoutFilter() {
        super.listener = new TimeoutListener();
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        invocation.setAttachment(TIMEOUT_FILTER_START_TIME, String.valueOf(System.currentTimeMillis()));
        return invoker.invoke(invocation);
    }

    static class TimeoutListener implements Listener {

        @Override
        public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
            String startAttach = invocation.getAttachment(TIMEOUT_FILTER_START_TIME);
            if (startAttach != null) {
                long elapsed = System.currentTimeMillis() - Long.valueOf(startAttach);
                if (invoker.getUrl() != null && elapsed > invoker.getUrl().getMethodParameter(invocation.getMethodName(), "timeout", Integer.MAX_VALUE)) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("invoke time out. method: " + invocation.getMethodName() + " arguments: " + Arrays.toString(invocation.getArguments()) + " , url is " + invoker.getUrl() + ", invoke elapsed " + elapsed + " ms.");
                    }
                }
            }
        }

        @Override
        public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {

        }
    }
}
  • TimeoutFilter继承了ListenableFilter,其构造器初始化的listener为TimeoutListener;invoke方法先记录开始执行的时间,之后执行结束时会回调Listener的onResponse或onError方法;TimeoutListener的onResponse会取出timeout_filter_start_time值,如果存在则计算执行耗时,在设置了有效timeout且耗时大于该timeout时,会打印warn日志

小结

TimeoutFilter继承了ListenableFilter,其构造器初始化的listener为TimeoutListener;invoke方法先记录开始执行的时间,之后执行结束时会回调Listener的onResponse或onError方法;TimeoutListener的onResponse会取出timeout_filter_start_time值,如果存在则计算执行耗时,在设置了有效timeout且耗时大于该timeout时,会打印warn日志

doc

  • TimeoutFilter
原文  https://segmentfault.com/a/1190000019571483
正文到此结束
Loading...