我写了一个老鼠包处理程序来测量处理程序链的执行时间。
public class EndpointMetricsEmitter implements Handler {
public static final String HANDLE_DURATION_METRIC = "HANDLE_DURATION_MILLIS";
private final MetricContext baseContext;
private MonitoringRegistry registry;
public EndpointMetricsEmitter(MonitoringRegistry monitoringRegistry) {
this.registry = monitoringRegistry;
this.baseContext = MetricContext.newContext(REST);
}
@Override
public void handle(Context ctx) throws Exception {
Instant start = Instant.now();
ctx.next();
Instant end = Instant.now();
long dur = Duration.between(start, end).toMillis();
MetricContext endpointCtx = this.baseContext.withService(ctx.getPathBinding().getDescription());
this.registry.timer(endpointCtx, HANDLE_DURATION_METRIC, dur);
}
问题是,我意识到 ctx.next()
是一个异步方法,它返回 void
.
是否有办法在链的最后一个处理程序返回时调用一个函数?
谢谢
一种方法是使用ChannelHandlerContext属性Map api。
我会做的是创建某种统计pojo,在第一个处理程序中初始化它,然后在你的最终处理程序中更新它。
这样做的一个好处是,管道中的每个处理程序都可以选择跟踪它的性能,并自己更新属性。