NodeJS集群,它真的需要吗?

Roy*_*hko 0 javascript node.js express server node-cluster

我决定要研究用NodeJS服务器处理大量流量的最佳方法是什么,我对2个数字海洋服务器进行了一次小测试,它有1GB RAM/2个CPU无群集服务器代码:

// Include Express
var express = require('express');

// Create a new Express application
var app = express();

// Add a basic route – index page
app.get('/', function (req, res) {
    res.redirect('http://www.google.co.il');
});

// Bind to a port
app.listen(3000);
console.log('Application running');
Run Code Online (Sandbox Code Playgroud)

群集服务器代码:

    // Include the cluster module
var cluster = require('cluster');
// Code to run if we're in the master process
if (cluster.isMaster) {
    // Count the machine's CPUs
    var cpuCount = require('os').cpus().length;

    // Create a worker for each CPU
    for (var i = 0; i < cpuCount; i += 1) {
        cluster.fork();
    }
// Code to run if we're in a worker process
} else {
    // Include Express
    var express = require('express');

    // Create a new Express application
    var app = express();

    // Add a basic route – index page
    app.get('/', function (req, res) {
        res.redirect('http://www.walla.co.il');
    });

    // Bind to a port
    app.listen(3001);
    console.log('Application running #' + cluster.worker.id);
}
Run Code Online (Sandbox Code Playgroud)

我向这些服务器发送了压力测试请求,除了集群服务器将处理更多请求但没有发生,两台服务器在同一负载上崩溃,尽管集群上运行了2个节点服务,非服务器上运行了1个服务-簇.

现在我想知道为什么?我做错了什么吗?

也许还有其他东西让服务器达到断点?两台服务器都以~800 rps的速度崩溃

jfr*_*d00 8

现在我想知道为什么?我做错了什么?

除了a之外,您的测试服务器不会执行任何操作res.redirect().如果您的请求处理程序基本上不使用CPU,那么您根本不会受CPU限制,并且您将无法从涉及更多CPU中受益.您的群集在处理传入连接时会遇到瓶颈,无论是否有群集,这些连接都将大致相同.

现在,为您的请求处理程序添加一些重要的CPU使用率,您应该得到不同的结果.

例如,更改为:

// Add a basic route – index page
app.get('/', function (req, res) {

    // spin CPU for 200ms to simulate using some CPU in the request handler
    let start = Date.now();
    while (Date.now() - start < 200) {}

    res.redirect('http://www.walla.co.il');
});
Run Code Online (Sandbox Code Playgroud)

运行测试是一件好事,但你必须要小心你正在测试什么.