首页 > 解决方案 > Node.js 集群仅用于 Express 应用程序中的特定功能

问题描述

我正在尝试在我的 Express 应用程序中运行 Node.js 集群,但仅限于一个特定功能。

我的应用是使用 express 应用生成器生成的标准 Express 应用。

我的应用程序最初会抓取电子商务网站以获取数组中的类别列表。我希望能够使用子进程同时抓取每个类别的产品。

我不想将整个 Express 应用程序放在子进程中。当应用程序启动时,我只需要一个进程来抓取初始类别。完成后,我只希望抓取产品的功能在集群中同时运行。

我尝试了以下方法:

委托-controller.js

var {em} = require('./entry-controller');
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;

class DelegationController {

links = [];

constructor() {
    em.on('PageLinks', links => {
        this.links = links;
        this.startCategoryCrawl();
    });
}

startCategoryCrawl() {
    if (cluster.isMaster) {
        console.log(`Master ${process.pid} is running`);

        for (let i = 0; i < numCPUs; i++) {
            cluster.fork();
        }
        cluster.on('exit', (worker, code, signal) => {
            console.log(`worker ${worker.process.pid} died`);
        });
    } else {
        console.log(`Worker ${process.pid} started`);
        process.exit();
    }
}
}

module.exports = DelegationController;

但后来我得到一个错误:

/ecommerce-scraper/bin/www:58
throw error;
^

Error: bind EADDRINUSE null:3000

我猜这是因为它正在尝试再次启动快速服务器,但它正在使用中。

我能做我想做的事,还是我误解了 Node.js 集群的工作原理?

标签: node.jsexpressnode-cluster

解决方案


我相信这不是您使用集群模块的情况。相反,您需要该child_process模块。该模块允许您创建一个单独的进程。这是文档


推荐阅读