要实现使用redis存储session会话状态达到集群效果,需要安装express-session、connect-redis模块
npm install express-session npm install connect-redis
这里redis我是采用的一个公用的模块,具体内容如下
配置文件config.js
exports.redisSentinel = { host: '192.168.199.55', port: 26379, opts: { auth_pass: '' } };
redis客户端的redis.js
var config = require('../../config'); var redisSentinel = require('redis-sentinel-client'); var client = redisSentinel.createClient(config.redisSentinel.port, config.redisSentinel.host, config.redisSentinel.opts); /*client.auth(config.redis.opts.auth_pass, function() { console.log('通过认证'); });*/ client.on('ready', function(res){ console.log('ready'); }); exports.get = function(key, callback) { client.on('connect', function(res) { client.get(key, callback); }); }; exports.set = function(key, value, callback) { client.on('connect', function(res) { client.set(key, value, callback); }); }; //设置值,同时设定过期时间 exports.setEx = function(key, value, timeout, callback) { client.on('connect', function(res) { client.set(key, value, callback); client.expire(key, timeout); }); };
在app中应用
var express = require('express'); var redis = require('./modules/system/redis'); var session = require('express-session'); var RedisStore = require('connect-redis')(session); var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(session({ resave: true, // don't save session if unmodified saveUninitialized: false, // don't create session until something stored secret: 'love', store: new RedisStore({ client : redis.client //代表引用公用的redis客户端 }), key:'express.sid' }));
说明:
参数
client 你可以复用现有的redis客户端对象, 由 redis.createClient() 创建
host Redis服务器名
port Redis服务器端口
socket Redis服务器的unix_socket
可选参数
ttl Redis session TTL 过期时间 (秒)
disableTTL 禁用设置的 TTL
db 使用第几个数据库
pass Redis数据库的密码
prefix 数据表前辍即schema, 默认为 "sess:"
感谢您的阅读,希望对您有帮助,本文版权归 #惊讶# 所有