Skip to content

升级 Http2 🌐

This content is not available in your language yet.

Feat 支持通过 HttpRequest.upgrade 方法将 HTTP/1.1 连接升级到 HTTP/2 协议。

HTTP/2协议栈

快速开始

操作示例如下:

Http2Demo.java
public class Http2Demo {
public static void main(String[] args) {
Feat.httpServer().httpHandler(request -> {
request.upgrade(new Http2Upgrade() {
@Override
public void handle(HttpRequest http2Request) {
HttpResponse response = http2Request.response();
response.setStatus(200);
response.send("HTTP/2响应");
}
});
}).listen();
}
}

核心机制

  1. 协议协商:通过Connection: UpgradeUpgrade: h2c头部完成握手
  2. 多路复用:基于Stream ID实现请求并发处理
  3. 头部压缩:采用HPACK算法压缩请求头
  4. 服务端推送:通过PushBuilder实现资源预推送

配置参数

Http2Upgrade 提供以下构造方法:

public Http2Upgrade() {
this(120000); // 默认空闲超时120秒
}
public Http2Upgrade(long idleTimeout) {
this.idleTimeout = idleTimeout;
}

性能优化

  1. 启用HPACK压缩:初始化时设置enableHeaderCompression=true
  2. 调整流控窗口:通过Http2Settings.initialWindowSize(1048576)
  3. 服务端推送配置:
http2Request.push()
.path("/static/style.css")
.send();
  1. 保持长连接:设置合理的idleTimeout