node.js - 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 集群的工作原理?
解决方案
我相信这不是您使用集群模块的情况。相反,您需要该child_process
模块。该模块允许您创建一个单独的进程。这是文档。
推荐阅读
- c# - 如何隐藏没有可见性属性的窗口?
- python - 如何将每个样本 1px 绘制到图像上?/ DPI 测量的方向是什么?
- bash - 仅在许多文件中的特定列上使用 grep?
- google-chrome - Chrome 扩展程序 - 侦听服务工作人员网络调用时的否定选项卡 ID (-1)
- flutter - 无法将 ListView 设置为 LayoutBuilder Widget (Flutter)
- java - jlist listModel arrayOutOfBounds 在 20 项
- mysql - Sequelize 从关联表中获取列的总和
- python - 如何计算转移概率
- macos-catalina - 无法解析平台 macosx 的产品类型“com.apple.product-type.system-extension”(在目标 SimpleFirewallExtension 中)
- css-variables - liteelement css函数中的CSS变量