如何使用带有 fork 的 nodejs 集群

问题描述

在我的 nodejs 应用程序中,使用 fork 进行集群无法按预期工作。应用负载测试,“每秒请求数”仅为 2,总错误数:最大请求数。更多在我的控制器文件 cluster.worker.kill(); 命令创建错误读取ECONNRESET强文本****"

注意:fork 方法文件事件是异步的

负载测试命令

**loadtest -n 10 -c 10 http://localhost:8080/rockets**

index.js 文件 ==> 应用聚类

  console.log("total cpu",numcpu);
  if (cluster.isMaster) {
    for (let i = 0; i < numcpu; i++) {
      cluster.fork();
    }
    cluster.on("exit",(worker,code,signal) => {
      console.log(`worker ${worker.process.pid} died`);
      cluster.fork();
    });
  } else {
    // app.listen(3000,() => console.log("server running" + process.pid));

    //connected express with port
    const PORT = process.env.PORT || 8080;
    app.listen(PORT,() => {
      console.log(
        chalk.green.inverse(
          `Server is running by process ${process.pid} on PORT ${PORT}`
        )
      );
    });
  }

路由器 ==> 控制器文件

exports.get_tierOne = async (req,res,next) => {
  let companyId = 4949871654;
  let companyName = "test";

  try {
    const processpath = path.join(
      __dirname,"..","9-services","tierone_nmc_rmc_calculation_process.js"
    );

    const child = fork(processpath);
    child.send({ companyId,companyName });

    child.on("message",(response) => {
      res
        .status(response.messageType)
        .json({ message: response.message + " PID::" + process.pid });
    });
    //cluster.worker.kill();
  } catch (err) {
    next(err);
  }
};

fork 文件==> tierone_nmc_rmc_calculation_process.js

process.on("message",async (payload) => {
  if (payload.companyId !== "") {
    const message = await parentTotalNrcMrc(
      payload.companyId,payload.companyName
    );
    //console.log("message",message);
    process.send(message);
  }
});

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)