Node.js Express using Session with Redis Cluster

Dependencies

  • express
  • express-session
  • connect-redis
  • ioredis
    $ npm install express express-session connect-redis ioredis

Redis – Single Node

  1. install & run redis
  2. run in cmd
    $ redis-cli
  3. run this in redis-cli
    redis> FLUSHALL
    redis> keys *
  4. then there are no keys in redis store.
  5. 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');
    });
  6. connect to ‘localhost:5000/session’. then you can show message ‘session saved’
  7. refresh web browser, then message change to ‘session already saved. user = test’
  8. you can show key that is created by express session
    redis> keys *

Redis – Multi Node

  1. 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'}
    ]);
    
  2. find keys in your cluster

댓글 남기기