序
本文主要研究一下 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