优秀的编程知识分享平台

网站首页 > 技术文章 正文

Node应用cluster,即可令进程不死,又可使性能最优

nanyue 2024-08-18 19:53:17 技术文章 7 ℃

例程奉上:

var cluster = require('cluster');
var PORT = +process.env.PORT || 1337;

if(cluster.isMaster)
{
    cluster.fork();
    cluster.fork();
    cluster.fork();
    //cluster.fork();

    cluster.on('disconnect', function(worker){
        console.error('disconnect!');
        cluster.fork();
    });

}else{

    var domain = require('domain');
    var server = require('http').createServer(function(req, res){

        var d = domain.create();
        d.on('error', function(er){

            //something unexpected occurred
            console.error('error', er.stack);
            try{
                //make sure we close down within 30 seconds
                var killtimer = setTimeout(function(){
                    process.exit(1);

                }, 30000);

                // But don't keep the process open just for that!
                killtimer.unref();

                //stop taking new requests.
                server.close();

                //Let the master know we're dead. This will trigger a
                //'disconnect' in the cluster master, and then it will fork
                //a new worker.

                cluster.worker.disconnect();

                //send an error to the request that triggered the problem
                res.statusCode = 500;
                res.setHeader('content-type', 'text/plain');
                res.end('Oops, there was a problem!\n');
            }catch (er2){

                //oh well, not much we can do at this point.
                console.error('Error sending 500!', er2.stack);
            }

        });

        //Because req and res were created before this domain existed,
        //we need to explicitly add them.
        d.add(req);
        d.add(res);

        //Now run the handler function in the domain.
        d.run(function(){

            //You'd put your fancy application logic here.
            //- handleRequest(req, res);
            res.end("hello www.jshaman.com" + cluster.worker.id);
            //res.write("error")
        });

    });

    server.listen(PORT);
}

CPU、磁盘、内存,在极限条件下,都可满负荷,用尽机器所有性能:

结束一个工作进程,便会自动开启另一个工作进程:

最近发表
标签列表