1. 核心模塊對比
特性 | http 模塊 (HTTP/1.1) | http2 模塊 (HTTP/2) |
---|---|---|
協議版本 | HTTP/1.1(文本協議) | HTTP/2(二進制協議) |
多路復用 | 不支持(需多個 TCP 連接) | 支持(單連接多流) |
頭部壓縮 | 無 | HPACK 壓縮算法 |
服務器推送 | 不支持 | 支持 |
TLS 依賴 | 可選(但生產環境建議啟用) | 強制要求 TLS(可通過 allowHTTP1 降級) |
Node.js 版本 | 所有版本 | 8.4.0+(實驗性),10.0.0+(穩定) |
2. 使用場景
-
http
模塊:- 傳統 HTTP/1.1 服務
- 簡單請求/響應模型
- 需要兼容舊客戶端或代理
- 無需 HTTP/2 高級特性
-
http2
模塊:- 高并發場景(如 API 服務、實時應用)
- 需要減少延遲(多路復用)
- 傳輸大量重復頭部(如 Cookies)
- 服務器推送資源(如提前發送 CSS/JS)
3. 代碼示例
HTTP/1.1 服務器
const http = require('http');const server = http.createServer((req, res) => {res.writeHead(200, { 'Content-Type': 'text/plain' });res.end('Hello HTTP/1.1!');
});server.listen(3000, () => {console.log('HTTP/1.1 server on port 3000');
});
HTTP/2 服務器(需 TLS)
const http2 = require('http2');
const fs = require('fs');const server = http2.createSecureServer({key: fs.readFileSync('localhost-privkey.pem'),cert: fs.readFileSync('localhost-cert.pem'),allowHTTP1: true // 允許 HTTP/1.1 降級
});server.on('stream', (stream, headers) => {stream.respond({'content-type': 'text/html',':status': 200});stream.end('<h1>Hello HTTP/2!</h1>');
});server.listen(3001, () => {console.log('HTTP/2 server on port 3001');
});
4. 關鍵注意事項
-
證書要求:
- HTTP/2 默認需要 TLS,可通過
insecure
選項禁用(僅限開發環境):const server = http2.createServer({ insecure: true });
- HTTP/2 默認需要 TLS,可通過
-
客戶端兼容性:
- 使用
http2.connect()
連接 HTTP/2 服務器:const client = http2.connect('https://localhost:3001'); const req = client.request({ ':path': '/' }); req.on('response', (headers) => {// 處理響應 });
- 使用
-
性能優化:
- 啟用
settings
配置優化流控:server.on('session', (session) => {session.settings({enablePush: true,initialWindowSize: 65535}); });
- 啟用
5. 遷移建議
-
漸進式遷移:
- 使用
allowHTTP1: true
讓服務器同時支持 HTTP/1.1 和 HTTP/2。 - 通過
ALPN
協議自動協商版本。
- 使用
-
工具鏈支持:
- 使用
curl --http2
或 Postman 測試 HTTP/2。 - 監控工具:Wireshark 或
nghttp2 -v
。
- 使用
官方文檔
- Node.js HTTP 模塊
- Node.js HTTP/2 模塊
如果需要更具體的場景實現(如雙向流、動態推送),請提供詳細需求!