[英]Get the number of received bytes in Netty for gzip chunked response
I'm trying to solve a problem in a description. 我正在尝试解决描述中的问题。 Currently I have this pipeline:
目前,我有以下管道:
p.addLast(sslCtx.newHandler(ch.alloc()));
p.addLast(new HttpClientCodec());
p.addLast(new MyCustomHttpContentDecompressor());
// p.addLast(new HttpObjectAggregator(1048576));
p.addLast(businessLogicHandler);
When server returns non chunked response, it contains Content-Length header. 服务器返回非分块响应时,它包含Content-Length标头。 I succeeded to retrieve this value in my custom HttpContentDecompressor just before it removes this header and performs gzip decompression.
在它删除此标头并执行gzip解压缩之前,我成功在我的自定义HttpContentDecompressor中检索了此值。
But when server decides to send chunked response, I'm out of luck since there's no Content-Length header. 但是,当服务器决定发送分块的响应时,由于没有Content-Length标头,我很不走运。 I tried HttpObjectAggregator but seems that it returns the number of decompressed bytes.
我尝试了HttpObjectAggregator,但似乎它返回了解压缩的字节数。 I also reviewed netty
traffic
package, but it solves a different task. 我也查看了网络
traffic
套餐,但它解决了另一项任务。
I feel that solution is simple, but I do not know netty well. 我觉得解决方案很简单,但是我对Netty不太了解。 Maybe there's a way to add one more handler to pipeline (ex. before decompressor), that will read all bytes in buffer, save the number and pass them further to pipeline?
也许有一种方法可以在管道中添加一个处理程序(例如在解压缩器之前),该处理程序将读取缓冲区中的所有字节,保存该数字并将其进一步传递给管道? Some code examples will be very helpful.
一些代码示例将非常有帮助。
Solution: 解:
public class TrafficInterceptorHandler extends ChannelInboundHandlerAdapter {
public static final String NAME = "trafficInterceptor";
private static Logger LOG = LoggerFactory.getLogger(TrafficInterceptorHandler.class);
private AtomicInteger readBytes = new AtomicInteger(0);
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof ByteBuf) {
ByteBuf byteBuf = (ByteBuf) msg;
readBytes.addAndGet(byteBuf.readableBytes());
} else {
LOG.warn("Received msg is not a ByteBuffer. Actual class: " + msg.getClass());
}
ctx.fireChannelRead(msg);
}
public int getReadBytes() {
return readBytes.get();
}
}
Should be added to pipeline before other handlers 应该在其他处理程序之前添加到管道中
p.addLast(TrafficInterceptorHandler.NAME, new TrafficInterceptorHandler());
p.addLast(sslCtx.newHandler(ch.alloc()));
p.addLast(new HttpClientCodec());
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.