使用节点集群时如何处理会话数据和app.locals数据

时间:2018-07-11 12:16:23

标签: node.js express node-cluster

我有一台服务器,该服务器使用群集的漂亮骨骼设置。但是在继续前进之前,我不知道是因为每个将作为工作程序实例产生的服务器实例都具有自己的明示app.locals和会话数据。那么如何确保来自单个用户的每个请求都到达首先处理该会话的节点实例。

在不同集群节点之间的nodejs中保留会话并表达app.locals数据的标准方法是什么

const cluster = require('cluster');

const numCPUs = require('os').cpus().length;

process.env.UV_THREADPOOL_SIZE=16;



if (cluster.isMaster) {

  console.log(`Master ${process.pid} is running from node B `);

  // Fork workers.
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
  //cluster.fork();

  cluster.on('exit', (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
  });
} else {
  // Workers can share any TCP connection
  // In this case it is an HTTP server
  const http = require('http');
  const sticky = require('sticky-session');
  const express = require('express');
  const app = express();
  const crypto = require('crypto');

  app.get('/',(req, res)=> {
    //res.writeHead(200);
    //res.end('hello world\n');
    //res.send(`${process.pid}`);
    let worker = cluster.worker.id;
    crypto.pbkdf2('adsadsdasdasdasdasd','bdsdasda',100000,512,'sha512',()=>{

            res.send(`Hello World!  from worker Id: ${worker} and process Id: ${process.pid} from server A`);
            console.log(`Worker with Process Id  ${process.pid} handled the request`);

    })

  });

   http.createServer(app).listen(8000);

  //var server = http.createServer(app);
  //sticky.listen(server,8000);

  //var server = http.createServer(app);

  console.log(`Worker  Process Id ${process.pid} started`);


}

0 个答案:

没有答案