我正在学习如何在我设置的小沙箱中扩展服务器。这是非常简单的代码:
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const instanceId = parseInt(Math.random() * 1000);
//Allow all requests from all domains & localhost
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "POST, GET");
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.get('/', function(req, res) {
console.log(`[${new Date()}] ${req.method} ${req.originalUrl} from ${req.ip} at ${instanceId}`);
res.send(`received at ${Date.now()} from ${instanceId}`);
});
app.listen(6069);
没有什么可疯狂的,只是吐出日期和收到请求的实例。
用于扩展nodejs服务器的pm2文档建议我运行:
pm2 start server.js -i 5
哪个工作得很好。这是我使用npm模块loadtest对其进行压力测试时的示例输出:
server-0 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 847
server-1 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 261
server-3 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 328
server-2 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 163
server-4 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 351
server-0 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 847
server-3 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 328
server-1 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 261
server-2 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 163
server-4 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 351
server-0 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 847
server-3 [Sun Aug 07 2016 00:13:53 GMT-0400 (EDT)] GET / from ::ffff:127.0.0.1 at 328
这是我的问题。为什么节点没有抛出端口6069正在使用的错误?多个服务器正在尝试使用该端口 - 但没有抱怨。为什么?
PM2创建了自己的“嵌入式负载均衡器,它使用循环算法来更好地在工作者之间分配负载”。因此,它基本上围绕您的应用程序包装负载均衡器,并将请求代理到它创建的每个节点。
使用循环调度策略时,主服务器接受()所有传入连接,并将该特定连接的TCP句柄发送给所选工作者(通过IPC)。