码迷,mamicode.com
首页 > Web开发 > 详细

nodejs 负载均衡

时间:2016-01-09 12:32:52      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

实际中会用pm2来处理,这里只是了解下原理和网络模块

 

教程:http://taobaofed.org/blog/2015/11/03/nodejs-cluster/

纠正:net.createServerHandle();

记录:http://www.jianshu.com/p/54b85f278695

代码:

master

const net = require(‘net‘);
const fork = require(‘child_process‘).fork;

var handle = net.createServerHandle(‘0.0.0.0‘, 3000);

for(var i=0;i<4;i++) {
   fork(‘./worker‘).send({}, handle);
}

 worker

const net = require(‘net‘);
process.on(‘message‘, function(m, handle) {
  start(handle);
});

var buf = ‘hello nodejs‘;
var res = [‘HTTP/1.1 200 OK‘,‘content-length:‘+buf.length].join(‘\r\n‘)+‘\r\n\r\n‘+buf;

function start(server) {
    server.listen();
    server.onconnection = function(err,handle) {
        console.log(‘got a connection on worker, pid = %d‘, process.pid);
        var socket = new net.Socket({
            handle: handle
        });
        socket.readable = socket.writable = true;
        socket.end(res);
    }
}

 解释,fork(‘/worker)->emit(‘message‘)

nodejs 负载均衡

标签:

原文地址:http://www.cnblogs.com/wang-jing/p/5115807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!