简体   繁体   English

NestJS 中的集群

[英]Cluster in NestJS

Why lib the cluster dont work in NestJS?为什么 lib cluster在 NestJS 中不起作用?
MY VERSION NODE: 18.1.0我的版本节点:18.1.0

IMPLEMENTATION:执行:

import cluster from 'cluster';
import os from 'os';

export function inCluster(callback: Function, workers? : number) {
    if(cluster.isPrimary) {
        process.on('SIGINT', function () {
            for(let id in cluster.workers) {
                cluster.workers[id].kill();
            }
            process.exit(0);
        });

        const cpus = os.cpus().length;
        if(workers == null || workers > cpus) workers = cpus;

        for(let i = 0; i < workers; i++) cluster.fork(); 
        
        cluster.on('online', function (worker) {
            console.log(`Worker ${worker.process.pid} is online`)
        }); 

        cluster.on('exit', (worker, code, signal) => {
            console.log(`worker ${worker.process.pid} died. Restarting`); 
            cluster.fork(); 
        });
    }

    callback();
}




ERROR:错误:

teste_cluster/src/cluster.ts:5
    if(cluster.isPrimary) {
            ^
TypeError: Cannot read properties of undefined (reading 'isPrimary')
    at inCluster (/home/simoes/repositories/teste_cluster/src/cluster.ts:5:13)
    at Object.<anonymous> (/home/simoes/repositories/teste_cluster/src/main.ts:10:10)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:827:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47




I trieng change of the import for this:我为此更改了导入:

import cluster from 'node:cluster';
import os from 'node:os';

as the nodejs documentation demonstrates:正如 nodejs 文档所示:
https://nodejs.org/dist/latest-v18.x/docs/api/cluster.html https://nodejs.org/dist/latest-v18.x/docs/api/cluster.html

You should try type: const cluster = require('cluster');您应该尝试输入: const cluster = require('cluster'); instead of import cluster from 'cluster';而不是import cluster from 'cluster'; . . In my case this solved the issue.就我而言,这解决了这个问题。 What is more you should consider type cluster.schedulingPolicy = cluster.SCHED_RR;更重要的是,您应该考虑 type cluster.schedulingPolicy = cluster.SCHED_RR; if you running your app on windows.如果您在 Windows 上运行您的应用程序。 More info at node-js-typescript-power-of-many-processes-cluster "Scheduling policy" section.更多信息在node-js-typescript-power-of-many-processes-cluster “调度策略”部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM