Using cluster in an Expressjs app

前端 未结 3 2008
天命终不由人
天命终不由人 2021-01-31 21:07

I\'m doing a little OJT on my first node project and, while I can stand up a simple server, the app is going to get hammered so using cluster seems like a good idea. I\'ve cobbl

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-31 21:46

    For anyone searching later, here's what I ended up with:

    var cluster = require( 'cluster' );
    var express = require( 'express' );
    var path    = require( 'path' );
    
    var port    = 3000;
    var root    = path.dirname( __dirname );
    var cCPUs   = require('os').cpus().length;
    
    if( cluster.isMaster ) {
      // Create a worker for each CPU
      for( var i = 0; i < cCPUs; 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.' );
      });
    }
    else {
      var app    = express();
      var routes = require( './routes' )( app );
    
      app
        .use( express.bodyParser() )
        .listen( port );
    }
    

    I'm still very early in the node learning curve, but the server starts and appears to have a working running on each core. Thanks to JohnnyH for getting me on the right track.

提交回复
热议问题