1.控制带宽
public class FlowMonitoringHandler extends GlobalChannelTrafficShapingHandler {
public FlowMonitoringHandler(ScheduledExecutorService executor, long writeGlobalLimit, long readGlobalLimit,
long writeChannelLimit, long readChannelLimit, long checkInterval) {
super(executor, writeGlobalLimit, readGlobalLimit, writeChannelLimit, readChannelLimit, checkInterval);
}
@Override
protected void doAccounting(TrafficCounter counter) {
super.doAccounting(counter);
MetricsUtils.counterN(MetricsConstants.METRICS_TRAFFIC_COUNTER_READ, counter.lastReadBytes());
MetricsUtils.counterN(MetricsConstants.METRICS_TRAFFIC_COUNTER_WRITE, counter.lastWrittenBytes());
// log.info("TrafficCounter, Read: {} KB, Write: {} KB", counter.lastReadBytes() / 1024, counter.lastWrittenBytes() / 1024);
}
}
判断lastReadBytes和lastWrittenBytes大小,超过大小如何处理,自动阻塞后续的写入操作
GlobalChannelTrafficShapingHandler flowMonitoringHandler = new FlowMonitoringHandler(finalEventExecutorGroup,
config.getWriteGlobalLimit(),
config.getReadGlobalLimit(),
config.getWriteChannelLimit(),
config.getReadChannelLimit(),
config.getCheckInterval());
bootstrap.group(boss, worker)
.channel(NioServerSocketChannel.class)
.childOption(ChannelOption.TCP_NODELAY, config.isTcpNodelay())
.handler(new LoggingHandler(LogLevel.DEBUG))
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(flowMonitoringHandler);
}
});
2.控制消息大小
public class WebSocketSizeLimitHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
private static final int MAX_FRAME_SIZE = 1024 * 1024; // 设置最大消息大小为1MB
@Override
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) {
if (frame instanceof TextWebSocketFrame || frame instanceof BinaryWebSocketFrame) {
if (frame.content().readableBytes() > MAX_FRAME_SIZE) {
// 消息过大,可以根据需要进行处理,例如关闭连接或发送错误消息
ctx.close();
} else {
// 消息大小合法,继续处理
// ...
}
} else {
// 非文本或二进制帧,继续处理
// ...
}
}
}