netty读写流量统计实例
所属分类 netty
浏览量 2304
增加 TraficCountHandler , 重写读写方法进行统计
@Sharable
public class TraficCountHandler extends ChannelDuplexHandler {
static final AtomicLong writeBytes = new AtomicLong(0);
static final AtomicLong readBytes = new AtomicLong(0);
重写 channelRead 和 write 方法
参考流量整形 GlobalTrafficShapingHandler 实现
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
long bytes = calculateSize(msg);
if(bytes>0){
readBytes.addAndGet(bytes);
}
ctx.fireChannelRead(msg);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
long bytes = calculateSize(msg);
if(bytes>0){
writeBytes.addAndGet(bytes);
}
ctx.write(msg, promise);
}
private long calculateSize(Object msg) {
if (msg instanceof ByteBuf) {
return ((ByteBuf) msg).readableBytes();
}
if (msg instanceof ByteBufHolder) {
return ((ByteBufHolder) msg).content().readableBytes();
}
return -1;
}
注意 一定要 加 @Sharable 注解
建立多个连接时报错
WARN bossGroup-3-3 io.netty.channel.ChannelInitializer io.netty.channel.ChannelInitializer.exceptionCaught(ChannelInitializer.java:92) - Failed to initialize a channel. Closing: [id: 0xfd9b8f2c, L:/127.0.0.1:6789 - R:/127.0.0.1:54219]
io.netty.channel.ChannelPipelineException: dyyx.echo.TraficCountHandler is not a @Sharable handler, so can't be added or removed multiple times.
dyyx.echo.TraficCountHandler is not a @Sharable handler, so can't be added or removed multiple times.
telnet 127.0.0.1 6789
输入 traffic 会 返回 读写字节数
{writeBytes=4352934, readBytes=4353028}
完整代码
https://gitee.com/dyyx/netty4demo/tree/master/src/main/java/dyyx/echo
https://gitee.com/dyyx/netty4demo/blob/master/src/main/java/dyyx/echo/TraficCountHandler.java
上一篇
下一篇
netty使用技巧
vert.x介绍
基于netty实例演示NIO BIO 异步和同步
netty空闲连接检测
netty 服务端启动日志
springboot应用安全防护