netty优化

This commit is contained in:
Guoqs
2024-12-15 14:33:29 +08:00
parent 0df516b440
commit 2a45ce83aa

View File

@@ -32,6 +32,9 @@ public class NettyServerManager implements CommandLineRunner {
@Resource
private ElectricBicyclesServerChannelInitializer electricBicyclesServerChannelInitializer;
private int bossGroupSize = Runtime.getRuntime().availableProcessors();
private int workerGroupSize = bossGroupSize * 2;
@Override
public void run(String... args) throws Exception {
startNettyServer(Constants.SOCKET_IP, 9011);
@@ -41,8 +44,8 @@ public class NettyServerManager implements CommandLineRunner {
public void startNettyServer(String host, int port) {
new Thread(() -> {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
EventLoopGroup bossGroup = new NioEventLoopGroup(bossGroupSize);
EventLoopGroup workerGroup = new NioEventLoopGroup(workerGroupSize);
try {
ServerBootstrap bootstrap = new ServerBootstrap()
@@ -51,14 +54,17 @@ public class NettyServerManager implements CommandLineRunner {
.handler(new LoggingHandler(LogLevel.DEBUG))
// .option(ChannelOption.SO_BACKLOG, 128) // 默认128
.option(ChannelOption.SO_BACKLOG, 1024)
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) // 启用池化内存分配器
// .option(ChannelOption.SO_REUSEADDR, true)
.childOption(ChannelOption.SO_KEEPALIVE, true) // 保持连接
// .childOption(ChannelOption.SO_RCVBUF, 64 * 1024) // 接收缓冲区
.childOption(ChannelOption.SO_RCVBUF, 1024 * 1024) // 接收缓冲区
// .childOption(ChannelOption.SO_SNDBUF, 64 * 1024) // 发送缓冲区
.childOption(ChannelOption.SO_SNDBUF, 1024 * 1024) // 发送缓冲区
.childOption(ChannelOption.TCP_NODELAY, true) // 禁用 Nagle 算法
.childOption(ChannelOption.SO_RCVBUF, 64 * 1024) // 接收缓冲区
.childOption(ChannelOption.SO_SNDBUF, 64 * 1024) // 发送缓冲区
.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(32 * 1024, 64 * 1024)) // 写缓冲水位
.childOption(ChannelOption.SO_REUSEADDR, true)
.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) // 启用池化内存分配器
// .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) // 启用池化内存分配器
.childHandler(nettyServerChannelInitializer)
.localAddress(new InetSocketAddress(host, port));
@@ -130,6 +136,7 @@ public class NettyServerManager implements CommandLineRunner {
.localAddress(new InetSocketAddress(host, port));
mqttBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline channelPipeline = ch.pipeline();
// 设置读写空闲超时时间