我想添加一个metricsHandler
来衡量请求-响应周期所花费的时间。
@Sharable
public class MetricCalcHandler extends ChannelDuplexHandler {
private static final AttributeKey<Long> TIME_TAKEN = AttributeKey.newInstance("time");
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
ctx.channel().attr(TIME_TAKEN).set(System.currentTimeMillis());
ctx.fireChannelRegistered();
}
@Override
public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
Long ms = System.currentTimeMillis() - ctx.channel().attr(TIME_TAKEN).get());
log.info("time taken " + ms);
ctx.deregister(promise);
}
}
public class MyInitializer extends ChannelInitializer<SocketChannel> {
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(new MetricCalcHandler());
p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(new HttpServerCodec());
p.addLast(new HttpObjectAggregator(1024 * 1024, true));
p.addLast(new Handler1());
p.addLast(new Handler2());
}
}
现在我的问题是
@Sharable
,但维护了频道的状态(按请求)。这是正确的吗?由于单个频道可在多个请求中共享,因此不会发生冲突/数据损坏。ChannelRegistered
中计算了处理开始时间,并在deregister
中完成了处理。那是正确的地方吗?或使用channelActive()/channelInActive()
方法?谢谢