Nodejs 集群和 expressjs 会话 [英] Nodejs Clustering and expressjs sessions

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

问题描述

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

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

}

我的问题是:每次单个用户点击随机节点实例,或者例如他第一次打开页面并点击节点 N4 并且直到他的会话到期之前,他每次请求都点击节点 N4?对于那些不理解我的问题的人,我将尝试解释我担心的问题:用户进入我的页面,他登录节点 N3,然后我将 req.session.userdata 设置为随机数据,他刷新页面并点击节点 N4,我可以从不同的节点访问 req.session.userdata 吗?这意味着用户有可能被随机注销,或者我只是不明白使用 express 进行集群的工作原理?

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?

推荐答案

你说得对,Connect/Express 中的内存会话存储不适合支持多个实例.解决方案是使用后备数据库实现会话存储.我的推荐是connect-redis,示例代码在Session Undefined- 使用 Connect-Redis/ExpressJS/Node

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

但是有几十种选择.

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

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