【发布时间】:2018-03-15 17:26:30
【问题描述】:
我一直使用redis 作为我的nodejs 服务器的内存存储。
会话也由 redis 管理。
目前我一直在做的是,每当我的服务器连接到它时,我都会刷新我的 redis,以便在服务器启动时没有会话存在
像这样:
redisClient.on('connect', function () {
redisClient.flushdb(function (err, succeeded) {
logger.debug("redis db cleared on startup--", succeeded); // will be true if successfull
});
});
我还将redis 用于其他一些数据存储,例如queue。
但现在我想在我的服务器上实现集群。
我的问题是如果我有 4 个cores,我的服务器上将运行 4 个节点实例。
num_processes = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
var workers = [];
// Helper function for spawning worker at index 'i'.
var spawn = function(i) {
console.log("spawing at index---",i);
workers[i] = cluster.fork();
console.log("----worker id-------", workers[i].id,"-------");
// Optional: Restart worker on exit
workers[i].on('exit', function(code, signal) {
console.log(`code is ${code} and signal is ${signal}`)
console.log(`worker ${workers[i].process.pid} died array index is ---${i}`);
console.log('respawning worker', i);
spawn(i);
});
workers[i].on('listening', () => {
workers[i].send({'index' : i });
});
};
// Spawn workers.
for (var i = 0; i < num_processes; i++) {
spawn(i);
} // Code to run if we're in a worker process
} else {
var redis = require('redis');
const sio_redis = require('socket.io-redis'),
redisClient = redis.createClient();
redisClient.on('connect', function () {
redisClient.flushdb(function (err, succeeded) {
logger.debug("redis db cleared on startup--", succeeded); // will be true if successfull
});
});
var RedisStore = require('connect-redis')(session);
const redisStore = new RedisStore({'host': 'localhost', 'port': 6379, 'client': redisClient});
var server = require('http').Server(app);
var listeningServer = server.listen(3002);
}
如果任何实例由于某种原因exit or die,它将清除redis中的所有会话和数据
我不希望这种情况发生。在这种情况下我应该如何使用 redis,以便清除与该实例对应的会话和数据?
【问题讨论】:
-
您将如何运行实例?
-
我已经添加了代码,实例是如何运行的