【发布时间】:2026-01-23 09:00:02
【问题描述】:
好的,所以我有一个用 Nodejs 编写的 API,它被集群化以利用使用“集群”模块的所有可用内核,总共有 4 个子进程。
const cluster = require('cluster');
我有一个进程('remNodeProcess'),我只需要派生 1 个实例,即我不希望每个工作节点派生自己的 'remNodeProcess' 实例。这个“remNodeProcess”不需要对每个子节点都可用。为此,我正在尝试使用“子进程”模块。
const childProcess = require('child_process');
我对 Node Clusters 有很好的阅读,并且已经使用了一段时间。集群按预期工作,我得到了预期的结果,但我似乎无法弄清楚如何分叉一个进程的单个实例。我只想要集群中这个进程的 1 个实例。
这是集群的完整代码:
const setupWorkerThreadNodes = () => {
// Get system CPUs
let SYS_CORE_COUNT = require('os').cpus().length;
// Read the Config Thread Configuration, if it exceeds the SYS_CORE_COUNT, set it to max usage, otherwise honour the Config
let coreCount;
if (webAppConfig.appConfig.nodeClusterConfiguration.mtMaxWorkerThreadCount) {
coreCount = webAppConfig.appConfig.nodeClusterConfiguration.mtMaxWorkerThreadCount;
} else if (webAppConfig.appConfig.nodeClusterConfiguration.mtMaxWorkerThreadCount > SYS_CORE_COUNT) {
coreCount = SYS_CORE_COUNT;
}
logMsg(`NODE_MASTER PID: ${process.pid}`);
console.log('NODE_CLUSTER Master is setting up Nodes... ');
// For each Core, create a node and push it to the system cluster array
for (let i = 0; i < coreCount; i++) {
console.log(`NODE_CLUSTER Master is setting up Node [${i}/${coreCount}]... `);
workers.push(cluster.fork({ WorkerName: `Worker${i}` }));
// When a Worker responds to the Master, log the response
workers[i].on('message', function (message) {
console.log(message);
});
}
// process is clustered on a core and process id is assigned
cluster.on('online', function (worker) {
console.log('Worker ' + worker.process.pid + ' is listening');
logMsg(`CLUSTER_NODE Child opened. PID: ${worker.process.pid}`)
});
// If the Workers count matches the CoreCount, we've opened the correct amount of threads
if (workers.length === coreCount) logMsg(`NODE_CLUSTER Array successfully established.`, 'info');
// if any of the worker process dies then start a new one by simply forking another one
cluster.on('exit', function (worker, code, signal) {
console.log('Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal);
logMsg(`CLUSTER_NODE Child terminated. PID: ${worker.process.pid}. Code: ${code}. Signal: ${signal}`)
console.log('Starting a new worker');
cluster.fork();
workers.push(cluster.fork());
// to receive messages from worker process
workers[workers.length - 1].on('message', function (message) {
console.log(message);
});
});
};
我尝试了以下方法:
if(cluster.isMaster){
const remNodeProcess= childProcess.fork('./background_workers/remNode.js');
remNodeProcess.send(pool, (err) => { console.log(err) })
}
当我使用此代码运行 API 时,remNodeProcess 没有打开。如果我使用以下代码(没有 IF 包装器):
const remNodeProcess= childProcess.fork('./background_workers/remNode.js');
remNodeProcess.send(pool, (err) => { console.log(err) })
我为每个孩子获得一个 remNodeProcess。
如何 fork 给定进程的一个实例?这可以从Master那里完成吗?
【问题讨论】:
标签: javascript node.js