本文主要研究一下dubbo的TimeoutFilterjava
dubbo-2.7.2/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ListenableFilter.javagit
public abstract class ListenableFilter implements Filter { protected Listener listener = null; public Listener listener() { return listener; } }
dubbo-2.7.2/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.javagithub
@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日誌apache