上一篇【第61篇】Netty性能调优——从10万到100万连接的优化之路
下一篇【第63篇】Netty压测与性能基准——Wrk/JMH实战测量吞吐量


一、系统优化脚本

#!/bin/bash
# 文件描述符
echo "* soft nofile 1000000" >> /etc/security/limits.conf
echo "* hard nofile 1000000" >> /etc/security/limits.conf

# 内核参数
cat >> /etc/sysctl.conf << EOF
net.core.somaxconn = 4096
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_max_tw_buckets = 5000
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
EOF
sysctl -p

二、systemd服务配置

# /etc/systemd/system/netty-server.service
[Unit]
Description=Netty Application Server
After=network.target

[Service]
Type=simple
User=app
WorkingDirectory=/opt/app
ExecStart=/usr/bin/java -Xmx4g -Xms4g -jar app.jar
ExecStop=/bin/kill -TERM $MAINPID
Restart=on-failure
RestartSec=10

# 优雅关闭
TimeoutStopSec=120
KillSignal=SIGTERM

[Install]
WantedBy=multi-user.target

三、JVM启动脚本

#!/bin/bash
JAVA_OPTS="-Xmx4g -Xms4g"
JAVA_OPTS="$JAVA_OPTS -XX:+UseG1GC"
JAVA_OPTS="$JAVA_OPTS -XX:MaxGCPauseMillis=200"
JAVA_OPTS="$JAVA_OPTS -XX:+HeapDumpOnOutOfMemoryError"
JAVA_OPTS="$JAVA_OPTS -XX:HeapDumpPath=/opt/logs/heap.hprof"
JAVA_OPTS="$JAVA_OPTS -Dio.netty.leakDetection.level=SIMPLE"
JAVA_OPTS="$JAVA_OPTS -Dio.netty.allocator.numHeapArenas=4"

# OOM自动重启
JAVA_OPTS="$JAVA_OPTS -XX:OnOutOfMemoryError='kill -9 %p'"

java $JAVA_OPTS -jar app.jar

四、应用内优雅关闭

public class ShutdownHook {
    public static void register(EventLoopGroup... groups) {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("收到SIGTERM,开始优雅关闭...");
            for (EventLoopGroup g : groups) {
                g.shutdownGracefully(30, 10, TimeUnit.SECONDS);
            }
            System.out.println("服务器已关闭");
        }));
    }
}

五、监控指标

// 暴露Netty指标
@Component
public class NettyMetrics {
    public Map<String, Object> getMetrics() {
        return Map.of(
            "boss.active", bossGroup.next().pendingTasks(),
            "worker.size", workerGroup.executorCount(),
            "pool.heap.used", PooledByteBufAllocator.DEFAULT.metric().usedHeapMemory(),
            "pool.direct.used", PooledByteBufAllocator.DEFAULT.metric().usedDirectMemory()
        );
    }
}

六、总结

维度 关键配置
文件描述符 ulimit -n 1000000
TCP参数 somaxconn, tw_reuse
服务管理 systemd + KillSignal=SIGTERM
JVM G1GC + OOM自动dump

上一篇【第61篇】Netty性能调优——从10万到100万连接的优化之路
下一篇【第63篇】Netty压测与性能基准——Wrk/JMH实战测量吞吐量


Logo

openEuler 是由开放原子开源基金会孵化的全场景开源操作系统项目,面向数字基础设施四大核心场景(服务器、云计算、边缘计算、嵌入式),全面支持 ARM、x86、RISC-V、loongArch、PowerPC、SW-64 等多样性计算架构

更多推荐