NodeJs

Nodejs 利用 express-cluster实行多线程

  • 通过命令安装 npm install express-cluster

express-cluster介绍: https://www.npmjs.com/package/express-cluster

  • server.js代码
Object.defineProperty(exports, '__esModule', {
  value: true,
});

const express = require('express');
var cluster = require('express-cluster');
const numCPUs = require('os').cpus().length;
global.workid

cluster(function (worker) {
  const app = express();
  const bodyParser = require('body-parser');
  app.use(bodyParser.json({ limit: '200mb' }));
  const router = require('./router');
  app.use('/', router);
  global.workid = worker.id
  
  const serverPort = process.env.PORT || 8000;
  var server = app.listen(serverPort, () => {
    console.log('Server Start processId =' + global.workid);
  });
  server.setTimeout(1200000)
  return server
}, {
  count: numCPUs
})
  • 当启动多线程以后,schedule定制任务也会启动多个。这样会造成一些麻烦,我们可以通过worker.id来控制一下,只执行一个定制任务。
const scheduleCronstyle = () => {
  var rule = new schedule.RecurrenceRule();
  rule.hour = [23];
  rule.minute = [10, 30, 50];
  schedule.scheduleJob(rule, () => {
    // 通过保存在global变量中的workid来控制, 多个线程 只执行一次schedule(workid = 1)
    if(global.workid!= 1) {
      return
    }
    xxxxxxxxxx
    console.log('scheduleCronstyle processId = ' + global.workid);
  });
};
scheduleCronstyle();