node构建最高性能的http1.1服务方案是什么
Node.js 最高性能 HTTP/1.1 服务方案
性能排名概览
┌─────────────────────────────────────────────────────────────┐
│ 性能排名 (req/sec) │
├─────────────────────────────────────────────────────────────┤
│ 1. uWebSockets.js ████████████████████████████ ~300k+ │
│ 2. Fastify █████████████████████ ~75k │
│ 3. Polka/0http ████████████████████ ~70k │
│ 4. Koa ████████████████ ~55k │
│ 5. Express ██████████████ ~45k │
│ 6. 原生 http █████████████████████ ~65k │
└─────────────────────────────────────────────────────────────┘
方案一:极致性能 - uWebSockets.js(推荐)
// server.js
const uWS = require('uWebSockets.js');
const cluster = require('cluster');
const os = require('os');
const PORT = 3000;
const numCPUs = os.cpus().length;
if (cluster.isPrimary) {
console.log(`Master ${process.pid} is running`);
// Fork workers
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker) => {
console.log(`Worker ${worker.process.pid} died, restarting...`);
cluster.fork();
});
} else {
uWS.App()
.get('/api/users', (res, req) => {
res.writeHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ users: [] }));
})
.get('/api/health', (res, req) => {
res.end('OK');
})
.any('/*', (res, req) => {
res.writeStatus('404').end('Not Found');
})
.listen(PORT, (token) => {
if (token) {
console.log(`Worker ${process.pid} listening on port ${PORT}`);
}
});
}
方案二:生态平衡 - Fastify(最推荐)
// server.js
const fastify = require('fastify');
const cluster = require('cluster');
const os = require('os');
const numCPUs = os.cpus().length;
// ============ 高性能配置 ============
const serverOptions = {
logger: false, // 生产环境关闭日志
trustProxy: true,
connectionTimeout: 30000,
keepAliveTimeout: 72000,
maxParamLength: 200,
bodyLimit: 1048576, // 1MB
caseSensitive: true,
ignoreTrailingSlash: false,
// HTTP/1.1 优化
http2: false,
https: null,
};
if (cluster.isPrimary) {
console.log(`Master ${process.pid} starting ${numCPUs} workers`);
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker) => {
cluster.fork();
});
} else {
const app = fastify(serverOptions);
// ============ 性能优化插件 ============
// JSON 序列化优化(提升 2-3x)
app.register(require('@fastify/response-validation'), {
ajv: {
removeAdditional: true,
useDefaults: true,
coerceTypes: true,
}
});
// 路由预编译
const schema = {
response: {
200: {
type: 'object',
properties: {
id: { type: 'integer' },
name: { type: 'string' }
}
}
}
};
app.get('/api/user/:id', { schema }, async (request, reply) => {
return { id: parseInt(request.params.id), name: 'John' };
});
// 启动服务
app.listen({ port: 3000, host: '0.0.0.0' });
}
方案三:原生极简 - http + Cluster
// server.js
const http = require('http');
const cluster = require('cluster');
const os = require('os');
const numCPUs = os.cpus().length;
const PORT = 3000;
// ============ 预编译响应 ============
const RESPONSES = {
json: Buffer.from(JSON.stringify({ status: 'ok', data: [] })),
headers: {
'Content-Type': 'application/json',
'Connection': 'keep-alive',
'Keep-Alive': 'timeout=72',
}
};
// 简易路由表
const routes = new Map([
['GET:/api/health', (req, res) => {
res.writeHead(200, RESPONSES.headers);
res.end(RESPONSES.json);
}],
['GET:/api/users', (req, res) => {
res.writeHead(200, RESPONSES.headers);
res.end(RESPONSES.json);
}]
]);
if (cluster.isPrimary) {
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
const server = http.createServer((req, res) => {
const key = `${req.method}:${req.url}`;
const handler = routes.get(key);
if (handler) {
handler(req, res);
} else {
res.writeHead(404);
res.end('Not Found');
}
});
// ============ Socket 层优化 ============
server.keepAliveTimeout = 72000;
server.headersTimeout = 75000;
server.maxHeadersCount = 100;
server.timeout = 120000;
server.listen(PORT, '0.0.0.0');
}
系统级优化配置
1. Node.js 启动参数
#!/bin/bash
# start.sh
node \
--max-old-space-size=4096 \
--max-semi-space-size=128 \
--optimize-for-size \
--gc-interval=100 \
--expose-gc \
server.js
2. Linux 系统调优
# /etc/sysctl.conf
# 网络优化
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_fin_timeout = 10
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_keepalive_time = 60
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_keepalive_intvl = 10
# 文件描述符
fs.file-max = 2097152
fs.nr_open = 2097152
# 应用
sysctl -p
3. 文件描述符限制
# /etc/security/limits.conf
* soft nofile 1000000
* hard nofile 1000000
架构对比总结
┌────────────────┬──────────────┬────────────┬──────────────┐
│ 方案 │ 性能 │ 易用性 │ 生态 │
├────────────────┼──────────────┼────────────┼──────────────┤
│ uWebSockets.js │ ⭐⭐⭐⭐⭐ │ ⭐⭐ │ ⭐⭐ │
│ Fastify │ ⭐⭐⭐⭐ │ ⭐⭐⭐⭐⭐ │ ⭐⭐⭐⭐ │
│ 原生 http │ ⭐⭐⭐⭐ │ ⭐⭐⭐ │ - │
│ Polka │ ⭐⭐⭐⭐ │ ⭐⭐⭐⭐ │ ⭐⭐⭐ │
└────────────────┴──────────────┴────────────┴──────────────┘
最终推荐
| 场景 | 推荐方案 |
|---|---|
| 极致性能优先 | uWebSockets.js + Cluster |
| 生产环境通用 | Fastify + Cluster(首选) |
| 微服务/简单API | 原生 http + Cluster |
| 需要兼容 Express 中间件 | Fastify(有适配层) |
90% 的场景推荐 Fastify:性能仅次于 uWebSockets.js,但生态完善、开发效率高。
好好学习天天向上,推荐一些http书籍:http 书籍
浙公网安备 33010602011771号