nodejs如何开启多线程,充分发挥多核cpu的性能?

本文探讨了如何在Node.js中利用多核CPU,通过启动多个进程来提升性能。引用了相关资源并提出了两种解决Session Data同步问题的方案:使用高级路由器或共享内存存储,推荐使用Redis或memcached实现数据池。还提出了利用Node.js运行多个网站的特性进行优化的可能性。

--在实际探讨前,先给出下面一个可能过的解决方案。

详细可见:http://blog.fens.me/nodejs-core-cluster/

<span style="font-size:18px;">var cluster = require('cluster'),
    numCPUs = require('os').cpus().length;
this.port=8001;

if (cluster.isMaster) {
    console.log(' num=' + numCPUs);
    for (var i = 0; i < numCPUs / 2; i++) {
        cluster.fork();
    }
    cluster.on('listening', function (worker, address) {
    });

} else if (cluster.isWorker) {
    http.createServer(exp).listen(this.port, function () {
        console.log(' server listening on = port='+ this.port);
    });
}</span>


别的解决方案。

Multiprocessor Deployment: Using a Proxy

参阅:http://www.tehnrd.com/host-multiple-node-js-apps-on-the-same-subdomain-with-heroku/

           和《learn nodejs》P220


 最容易的:每个核跑一个node进程。就这样ko。 

 假设我们的servers-list是长这样的,服务器是在81-83口监听。

{ "servers": [ 

{"host": "localhost","port": "8081"}, 

{"host": "localhost","port": "8082"}, 

{"host": "localhost","port": "8083"} ] }

  

<span style="font-size:18px;">//在package.json加多这个
"dependencies": {
                 "http-proxy": "0.8.x"
}</span>


 ---实际代码可能长这样。

//Listing 10.2 A Round-Robin Proxy Load Balancer (roundrobin.js)
var httpProxy = require('http-proxy'),
fs = require('fs');
var servers = JSON.parse(fs.readFileSync('server_list.json')).servers;
var s = httpProxy.createServer(function (req, res, proxy) {
var target = servers.shift(); //1. Remove first server
proxy.proxyRequest(req, res, target); //2. Re-route to that server
servers.push(target); //3. Add back to end of list
});
s.listen(8080);

//然后每个serves就简单这样就好了

var http = require('http');
if (process.argv.length != 3) {
 console.log("Need a port number");
 process.exit(-1);
}
var s = http.createServer(function (req, res) {
 res.end("I listened on port " + process.argv[2]);
});
s.listen(process.argv[2]);

//试运行下

linux版

$ node simple.js 8081 &
$ node simple.js 8082 &
$ node simple.js 8083 &


WINDOWS版
node simple.js 8081
node simple.js 8082
node simple.js 8083


这时候面临的另一个问题就是关于 Session Data。




Because each Node server stores its own record of sessions in its own memory store, when two

requests from the same client go to two different node processes, they have different ideas of

current state of the session data from the client and get horribly confused quickly. You have

two obvious ways to solve this problem:

1.Implement a more advanced router that remembers to which Node server requests from
a particular client are being sent and ensure that all traffic continues to be routed in the
same way for the same client.
2. Somehow pool the memory stores that the session data uses so that all Node processes
can access it.
I prefer the second solution because it is quite simple to implement and a much less complicated solution.


 //所以为了实现这个pool,显然我们需要类似mencached或者redis这样的东西。来高效的存取数据,供大家使用。

 To set up this solution, you need to first choose a pooled memory store. The obvious candidates for this arememcachedandRedis, both of which are effectively largememory-based key/
value stores
that can be spread across different computers. You work with memcached in this
chapter because it’s entirely adequate for your needs and extremely lightweight. Your setup
should look similar to that shown in Figure 10.3 .


//然后我们的代码调整成过这样

<span style="font-size:18px;">var express = require('express');
// pass the express obj so connect-memcached can inherit from MemoryStore
var MemcachedStore = require('connect-memcached')( express);
var mcds = new MemcachedStore({ hosts: "localhost:11211" });
var app = express()
 .use(express.logger('dev'))
 .use(express.cookieParser())
 .use(express.session({ secret: "cat on keyboard",
 cookie: { maxAge: 1800000 },
 store:mcds }))
 .use(function(req, res){
 var x = req.session.last_access;
 req.session.last_access = new Date();
 res.end("You last asked for this page at: " + x);
 })
 .listen(8080);</span>

 

//瞎想的方案

我们知道nodejs是支持一个servers运行多个websites的,那么我们可以利用这个特性吗?

Listing 10.3 Virtual Hosts in Express (vhost_server.js)
var express = require('express');
varone = express();
one.get("/", function(req, res){
 res.send("This is app one!")
});
// App two
vartwo = express(); 
two.get("/", function(req, res){
 res.send("This is app two!")
});
// App three
varthree = express();
three.get("/", function(req, res){
 res.send("This is app three!")
});
// controlling app
varmaster_app = express();
master_app.use(express.logger('dev'));
master_app.use(express.vhost ('app1',one ))
master_app.use(express.vhost ('app2',two ));
master_app.use(express.vhost ('app3',three ));
master_app.listen(8080)


 //未完待续。。。。。

//下次再写


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值