HttpServer 配置
HttpServer.create()
.port(8080) // 监听端口
.host("0.0.0.0") // 绑定地址
// 1 个 selector 线程 + 4 个 worker 线程
.runOn(LoopResources.create("eventd", 1, 4, true))
.option(ChannelOption.SO_BACKLOG, 128) // accept 队列(server 端 option)
.childOption(ChannelOption.SO_KEEPALIVE, true) // TCP keep-alive
.childOption(ChannelOption.TCP_NODELAY, true) // 禁用 Nagle
.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
new WriteBufferWaterMark(32 * 1024, 128 * 1024)) // 写水位线
.handle((req, res) -> ...)
.bindNow();
优雅关闭
DisposableServer server = HttpServer.create().port(8080).handle(...).bindNow();
Runtime.getRuntime().addShutdownHook(new Thread(() ->
server.disposeNow(Duration.ofSeconds(10))));
server.onDispose().block();
HttpClient 配置
ConnectionProvider provider = ConnectionProvider.builder("my-pool")
.maxConnections(50)
.maxIdleTime(Duration.ofMinutes(5))
.maxLifeTime(Duration.ofMinutes(30))
.pendingAcquireMaxCount(100)
.pendingAcquireTimeout(Duration.ofSeconds(10))
.lifo()
.build();
HttpClient.create(provider)
.baseUrl("https://api.example.com")
.responseTimeout(Duration.ofSeconds(30))
.followRedirect(true)
.compress(true) // 自动处理 gzip
.headers(h -> h.set("User-Agent", "eventd-v2"));
SSL/HTTPS
HttpServer.create()
.secure(spec -> spec.sslContext(
SslContextBuilder.forServer(certChain, privateKey).build()))
.handle((req, res) -> ...)
.bindNow();
客户端信任所有证书(仅开发):
HttpClient.create()
.secure(spec -> spec.sslContext(
SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build()));
HTTP/2
HttpServer.create()
.protocol(HttpProtocol.H2, HttpProtocol.HTTP11) // 优先 H2,回退 H1
.handle((req, res) -> ...)
.bindNow();
浏览器场景下 HTTP/2 需要 TLS + ALPN;明文 h2c 只适合受控的内部客户端,且需要客户端明确使用 prior-knowledge 模式。
常用 ChannelOption
| Option | 说明 | 建议值 |
|---|---|---|
SO_BACKLOG | TCP accept 队列(已完成握手、等待应用 accept) | 128–1024 |
SO_KEEPALIVE | TCP 保活探测 | true |
TCP_NODELAY | 禁用 Nagle 算法 | true(延迟敏感) |
SO_RCVBUF | 接收缓冲区 | 系统默认 |
SO_SNDBUF | 发送缓冲区 | 系统默认 |
WRITE_BUFFER_WATER_MARK | Netty 写水位线 | 低 32K 高 128K |
CONNECT_TIMEOUT_MILLIS | 客户端连接超时(HttpClient.option) | 3000ms |
小结
本附录覆盖 Reactor Netty 服务端/客户端/SSL/HTTP2 的核心配置。不要「为了显式」把所有默认值都重写一遍:默认的线程数、水位线和超时在多数场景是合理的,只显式设置那些经过压测或故障验证的参数,并在配置旁注明原因。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。