javascript - NodeJS集群,真的需要吗?

标签 javascript node.js express server node-cluster

我决定研究一下用 NodeJS 服务器处理大量流量的最佳方法是什么,我在 2 个具有 1GB RAM/2 个 CPU 的 digital ocean 服务器上做了一个小测试 无集群服务器代码:

// 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');

集群服务器代码:

    // 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);
}

我向这些服务器发送了压力测试请求,但集群服务器将处理更多请求,但这并没有发生,两台服务器在相同的负载上崩溃了,尽管 2 个 Node 服务在集群上运行,1 个服务在非集群上运行。

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

也许还有其他原因使服务器达到断点?两台服务器均在约 800 rps 时崩溃

最佳答案

Now i wonder why ? did i do anything wrong?

您的测试服务器除了 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');
});

运行测试是一件很棒的事情,但您必须小心您正在测试的内容。

关于javascript - NodeJS集群,真的需要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48050405/

相关文章:

javascript - 如何仅在需要时自动更新 Django 页面?

javascript - 获取数组元素的所有值

javascript - 负十进制数和正十进制数的正则表达式

javascript - 在启用监视和启动服务器的情况下运行 webpack

javascript - 我使用 auth0 进行用户身份验证,并且有一个用于 CRUD 帖子的 API(标题、img、desc)。如何对 CRUD api 进行经过身份验证的调用?

javascript - 使用 Express JS 的 Angular 模板组件

javascript - 如何更新这个 Reactjs 选择

javascript - 找不到 'core-js' 的类型定义文件

javascript - 意外的标记)node js eval 函数

apache - 避免nodejs和apache的80端口冲突