Nodejs聚类和expressjs会话 [英] Nodejs Clustering and expressjs sessions

查看:134
本文介绍了Nodejs聚类和expressjs会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建将利用多核机器(a.k.a.集群)的nodejs应用程序,并且我有一个关于会话的问题。我的代码如下所示:

  var cluster = exports.cluster = require('cluster'); 
var numCPUs = require('os')。cpus()。length;

if(cluster.isMaster){

for(var i = 0; i< numCPUs; i ++){
cluster.fork();
}

cluster.on('exit',function(worker,code,signal){
console.log('worker'+ worker.process.pid +' 。尝试重生...');
cluster.fork();
});

} else {

// spawn express etc

}
一个用户进入我的页面,他在节点N3上登录,然后将req.session.userdata设置为随机数据他刷新页面,他点击了节点N4,我能否从不同的节点访问req.session.userdata?这意味着用户有机会随机注销,或者我只是不了解如何使用express进行聚类?

解决方案

p>您正确地说,Connect / Express中的内存会话存储不适合支持多个实例。解决方案是使用后台数据库实现会话存储。我的建议是connect-redis,示例代码位于会话未定义 - 使用Connect-Redis / ExpressJS / Node



但是有几十个选项。


I'm trying to build nodejs application which will take advantage of multicore machines ( a.k.a. clustering ) and I got a question about sessions. My code looks like this:

var cluster = exports.cluster = require('cluster');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {

  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.process.pid + ' died. Trying to respawn...');
    cluster.fork();
  });

} else {

//spawn express etc

}

My question is: Everytime a single user hits random node instance or for example the first time he opens the page and hits node N4 and till his session expires, he hit node N4 on every request? For those who didn't understand my question, I will try to explain what I'm worried about: A user enters my page, he login on node N3, then I set req.session.userdata to a random data, he refreshes the page and he hit Node N4, will I be able to access req.session.userdata from different Node? That mean there is a chance for the user to get randomly logged out or I'm just not understanding how clustering with express works?

解决方案

You're correct that the in memory session store in Connect/Express is unsuitable for supporting more than one instance. The solution is to implement a session store with a backing database. My recommendation is connect-redis, and example code is at Session Undefined - Using Connect-Redis / ExpressJS / Node

But there are dozens of options.

这篇关于Nodejs聚类和expressjs会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆