Dependencies
- express
- express-session
- connect-redis
- ioredis
$ npm install express express-session connect-redis ioredis
Redis – Single Node
- install & run redis
- run in cmd
$ redis-cli
- run this in redis-cli
redis> FLUSHALL redis> keys *
- then there are no keys in redis store.
- and make js file for running express. refer below code
var express = require('express'); var app = express(); var session = require('express-session'); var RedisStore = require('connect-redis')(session); var Redis = require('ioredis'); var redisClient = new Redis({port: 6379, host: 'localhost'}); app.use(session({ secret: 'redis-session-test', store: new RedisStore({client: redisClient}), resave: false, saveUninitialized: true })); app.get('/session', function (req, res) { var session = req.session; console.log(session.user); if (session.user) { res.send('session already saved. user = ' + session.user); } else { session.user = 'test'; res.send('session saved'); } }); app.listen(5000, function () { console.log('Web Console @ 127.0.0.1: 5000'); });
- connect to ‘localhost:5000/session’. then you can show message ‘session saved’
- refresh web browser, then message change to ‘session already saved. user = test’
- you can show key that is created by express session
redis> keys *
Redis – Multi Node
- change code, redisClient in upper code. make sure that add all node ip in your cluster to option.
var redisClient = new Redis.Cluster([ {port: 6379, host: 'your-cluster-ip-1'}, {port: 6379, host: 'your-cluster-ip-2'}, {port: 6379, host: 'your-cluster-ip-3'}, {port: 6379, host: 'your-cluster-ip-4'} ]);
- find keys in your cluster