【发布时间】:2020-02-29 03:35:30
【问题描述】:
我正在尝试在我的 Express 应用程序中运行 Node.js 集群,但仅限于一个特定功能。
我的应用是使用 express 应用生成器生成的标准 Express 应用。
我的应用最初会抓取电子商务网站以获取数组中的类别列表。然后我希望能够使用子进程同时抓取每个类别的产品。
我不想将整个 Express 应用程序放在子进程中。当应用程序启动时,我只需要一个进程来抓取初始类别。完成后,我只希望抓取产品的功能在集群中同时运行。
我尝试了以下方法:
delegation-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.js express node-cluster