我正在尝试为多个TCP客户端连接实现netty流量处理程序。将流量处理程序添加到管道中就可以了。我可以每cumulativeReadBytes
毫秒来监视一个TCP客户端的cumulativeWrittenBytes
和checkInterval
值。我正在使用doAccounting
作为替代方法。
但是,当涉及多个TCP客户端连接时,问题就开始了。每个单个TCP客户端连接都会调用doAccounting
(当然,每个checkInterval
值也一样),但这会破坏调度,并导致doAccounting
方法几乎无限期地被大量TCP客户端调用连接。 (基本上,将为每个客户端连接创建一个新的定期呼叫。对于通过侦听端口接收的所有连接,我需要一个单一呼叫)
是否有任何方法可以在单个doAccounting
调用中全局监视所有TCP客户端连接的流量?
谢谢。
这是我的服务器处理程序方法:
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100)
.childOption(ChannelOption.SO_KEEPALIVE, true).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel argSocketChannel) throws Exception {
ChannelPipeline pipeline = argSocketChannel.pipeline();
pipeline.addLast(new ReadTimeoutHandler(21600));
pipeline.addLast(new MyTrafficHandler(5000));
pipeline.addLast(new MyEncoder());
pipeline.addLast(new MyDecoder(), new MyHandler(argProducer, argHandler, serverName));
}
});
ChannelFuture future = b.bind(argPort).sync();
future.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
这是MyTrafficHandler
类:
public class MyTrafficHandler extends ChannelTrafficShapingHandler {
public MyTrafficHandler(long checkInterval) {
super(checkInterval);
}
@Override
protected void doAccounting(TrafficCounter counter) {
System.out.println(counter.cumulativeReadBytes() + ":::" + counter.cumulativeWrittenBytes());
counter.resetCumulativeTime();
}
}