node中的开启多进程是用cluster吗?大家看看我下面代码有问题没
发布于 2年前 作者 peiweippww 1015 次浏览

main.js:

var cluster = require( 'cluster' );
var os = require( 'os' );

if( cluster.isMaster ) {
    cluster.on( 'exit', function( worker, code, signal ) {
        console.log( 'worker #' + worker.id + ' died, and try restarting...' );
        cluster.fork();
    });
    cluster.on( 'fork', function( worker ) {
        console.log( 'worker #' + worker.id + ' is forking.' );
    });
    cluster.on( 'online', function( worker ) {
        console.log( 'Yay, the worker responded after it was forked' );
    });
    cluster.on( 'listening', function( worker, address ) {
        console.log( 'A worker with #'+ worker.id + ' is now connected to ' + address.address + ':' + address.port );
    });
    cluster.on( 'disconnect', function( worker ) {
        console.log( 'The worker #' + worker.id + ' has disconnected' );
    });
    os.cpus().forEach(function() {
        cluster.fork();
    });
} else {
    var server = require( 'server.js' );
    var router = require( 'router.js' );

    server.start( router.route );
}

process.on( 'SIGTERM', function() {
    for( var id in cluster.workers ) {
        process.kill( id );
    }
    process.exit( 0 );
});

process.on( 'message', function( msg ) {
    console.log( 'process on message,and msg is : ' + msg );
});

server.js:

var net = require( 'net' );
var HOST = '127.0.0.1';
var PORT = 6969;
var Server = {};
var cluster = require( 'cluster' );

function start( route ) {
    Server = net.createServer( function( socket ) {
        //多进程监控接受
        console.log('Worker #' + cluster.worker.id + ' has a request');
        socket.on( 'data', function( data ) {
            //下面是业务相关代码
            route( socket, data );
        });
        socket.on( 'error', function( err ) {
            if( err.code == 'EADDRINUSE' ) {
                console.log( 'port ' + PORT + 'is using by other Server' );
            }
        });
        socket.on( 'close', function( msg ) {
            console.log( 'socket closed' );
        });
    });
    Server.listen( PORT, HOST );
    console.log( 'Server on.' );
}

exports.start = start;
3 回复

代码高亮下吧,哥!

好了,哥已高亮~

var server = require( ‘server.js’ ); var router = require( ‘router.js’ );

不知道你版本, 这个在node 3.x版本里是不行的。要这样写: var server = require( ‘./server’ ); var router = require( ‘./router’ );

回到顶部