Nodejs【单机】多进程模式集群实例:
1、安装:npm install -s cluster
2、服务代码:
var debug = require('debug');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var mockServer = function () {
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
process.env.PORT = 8103;
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function () {
console.log('服务启动:' + server.address().port);
});
}
module.exports = exports = mockServer;
3、启动文件加集群模式:
var path = require("path");
var mockfile = path.join(__dirname, './', 'mockServer');
var mockServer = require(mockfile);
var cluster = require('cluster')
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log("宿主启动...");
//var data = 0;
for (var i = 0; i < numCPUs; i++) {
//cluster.fork();
var worker_process = cluster.fork();
//侦听子进程的message事件
worker_process.on('message', function (msg) {
if (msg.cmd && msg.cmd == 'notifyRequest') {
//data++;
//console.log('DATA VALUE : %d ', data);
}
});
}
cluster.on('listening', function (worker, address) {
//console.log('pid:' + worker.process.pid);
});
cluster.on('exit', function (worker, code, signal) {
console.log('pid:' + worker.process.pid + ' 重启');
setTimeout(function () { cluster.fork(); }, 2000);
});
} else {
var server = new mockServer();
process.on('message', function (msg) {
if (msg === 'shutdown') {
// initiate graceful close of any connections to server
}
});
console.log('worker #' + cluster.worker.id + ",pid:" + cluster.worker.process.pid);
//process.send({ cmd: 'notifyRequest' });
}