该文档对于实现Throng来使用Heroku创建其他Webworker看起来非常简单。话虽如此,它给我留下了两个问题:

1)我还需要安装集群吗?根据我的阅读,Throng是Cluster的抽象,但是我没有看到Cluster包含在下载中。我错过了什么吗,还是Throng准备好开箱了?

2)我将这几行代码放在哪里? Angular Fullstack在服务器目录中有一个服务器目录和一个app.js文件。这是我最好的选择,但我可以想象,最好将它放在config目录中,甚至放在其他地方。

3)我需要什么顺序才能使用Throng?我了解,如果事情不正常,可能会使事情搞砸。如果app.js是放置var throng = require('throng')的正确位置。

以下链接是我对Throng上的指示的引用:
https://github.com/goodeggs/heroku-web-cluster

我将以下代码放在“启动服务器”下的app.js文件中:

var throng = require('throng');
var WORKERS = process.env.WEB_CONCURRENCY || 1;
var start = function(){
  process.on('SIGTERM', function() {
    console.log('Worker exiting');
    process.exit();
  });
}
throng(start, {
  workers: 1,
  lifetime: Infinity,
});

当我这样做时,在本地部署终端时,我会收到一个快速重复的错误消息:
Error: bind EADDRINUSE
    at exports._errnoException (util.js:746:11)
    at cb (net.js:1178:33)
    at rr (cluster.js:592:14)
    at Worker.<anonymous> (cluster.js:563:9)
    at process.<anonymous> (cluster.js:692:8)
    at process.emit (events.js:129:20)
    at handleMessage (child_process.js:324:10)
    at Pipe.channel.onread (child_process.js:352:11)
Debugger listening on port 5889
events.js:85
      throw er; // Unhandled 'error' event

        ^

最佳答案

var express = require('express');
var cluster = require('cluster'); //no need to download anything
var os = require('os'); //no need to download anything

if(cluster.isMaster) {
   var numWorkers = os.cpus().length;
   console.log('Master cluster setting up ' + numWorkers + ' workers...');

   for(var i = 0; i < numWorkers; i++) {
       cluster.fork();
   }

   cluster.on('online', function(worker) {
       console.log('Worker ' + worker.process.pid + ' is online');
   });

   cluster.on('exit', function(worker, code, signal) {
       console.log('Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal);
       console.log('Starting a new worker');
       cluster.fork();
   });
} else {
   var app = require('express')();
   var server = require('http').createServer(app);
   require('./config/express')(app);
   require('./routes')(app);

   // Start server
   server.listen(config.port, config.ip, function () {
     console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
   });
}

09-12 01:41