首页 > 解决方案 > pm2 不能 fork 包含原始集群代码的 nodejs

问题描述

我的应用程序是一个在内部使用原始 nodejs 集群代码的应用程序,并由节点 ./dist/main.js 运行,但是当我使用 pm2 start ./dist/main.js 时它出错了

//my code

import cluster from 'cluster'
import http from 'http'

if(cluster.isMaster){
    (async()=>{
        const master = await (await import('./master'))
        async function onMsg(pid:number,type?:string,num?:number,data?:{db:any,apiName:any,args:Array<any>}){
            console.log(`master receiving message from cluster ${pid}`)
            try{
                let result = await master.publishMission(type,data)
                // console.log(`${type} finish mission and send back to koa cluster ${pid}`)
                cluster.workers[pid].send({num:num,status:true,data:result})
            }catch(err){
                cluster.workers[pid].send({num:num,err})
            }
        }
        //cluster nums
        for(let i=0;i<1;i++){
            cluster.fork()
        }
        cluster.on('message',(worker,msg)=>{
            onMsg(worker.id,...msg)
        })
        cluster.on('exit', (worker, code, signal) => {
            console.log('worker %d died (%s). restarting...',worker.process.pid, signal || code);
            cluster.fork();
          });
    })()
}else{
    (async()=>{
        const app = await (await import('./app')).app
        try{
            http.createServer(app).listen(5000)`enter code here`
            console.log("fork new koa server",process.pid)
        }catch(err){
            console.log(err)
        }
    })()
}

//错误日志 TypeError: 在 EventEmitter 找到不可调用的@@iterator。(C:\Users\yany\project\Jmrh_Warehouse\src\main.ts:22:13) 在 EventEmitter.emit (events.js:315:20) 在 Worker。(internal/cluster/master.js:174:13) 在 ChildProcess 的 Worker.emit (events.js:315:20)。(internal/cluster/worker.js:32:12) 在 ChildProcess.emit (events.js:315:20) 在发射 (internal/child_process.js:903:12) 在 processTicksAndRejections (internal/process/task_queues.js: 81:21)TypeError:在 EventEmitter 发现不可调用的 @@iterator。(C:\Users\yany\project\Jmrh_Warehouse\src\main.ts:22:13) 在 EventEmitter.emit (events.js:315:20) 在 Worker。(internal/cluster/master.js:174:13) 在 ChildProcess 的 Worker.emit (events.js:315:20)。(internal/cluster/worker.js:32:12) 在 ChildProcess.emit (events.js:315:20) 在发射 (internal/child_process.js:903:

标签: node.jspm2

解决方案


pm2 在内部实现集群。

所以端口共享可能有问题。

其中:dist/main.js

(async()=>{
        const app = await (await import('./app')).app
        try{
            http.createServer(app).listen(5000)`enter code here`
            console.log("fork new koa server",process.pid)
        }catch(err){
            console.log(err)
        }
    })()

pm2 start dist/main.js -i max可能会奏效。 -i以集群模式启动 pm2。

https://pm2.keymetrics.io/docs/usage/cluster-mode/


推荐阅读