redis 03. koa-session connection and redis nodejs

AnSo koa-session

yarn add koa-session  

Placed koa-session redis

const session = require('koa-session');
const Redis = require('ioredis');
const redis = new Redis();


// placed koa-session
  server.keys = ['dev secret key'];
  const CONFIG = {
    key: 'ig',
    store: new RedisSessionStore(redis)
  };
  server.use(session(CONFIG, server));
// set session
  router.get('/set/user', async ctx => {
    ctx.session.user = {
      name: 'js',
      age: 29
    };
    ctx.body = 'success';
  });
  server.use(router.routes());  

  

koa-session store configuration

// connection of some methods redis

/**
 * Return the module name is actually used redis
 * @param {*} sid key
 */
function getSessionId(sid) {
  return `ssid:${sid}`;
}

class RedisSessionStore {
  constructor(client) {
    // pass an instance of redis
    this.client = client;
  }

  /**
   * Get session data from redis
   * @param {*} sid key
   */
  async get(sid) {
      console.log('get sid',sid)
    const id = getSessionId(sid);
    const data = await this.client.get(id);
    if (!data) {
      return null;
    }
    try {
      const result = JSON.parse(data);
      return result;
    } catch (err) {
      console.error(err);
    }
  }

  /**
   * Data is stored in session to redis
   * @param {*} sid key
   * @param {*} sess value
   * @Param {*} ttl expiration time
   */
  async set(sid, sess, ttl) {
    console.log('set sid',sid)
    const id = getSessionId(sid);
    if (typeof ttl === 'number') {
      ttl = Math.ceil(ttl / 1000);
    }
    try {
      const sessStr = JSON.stringify(sess);
      if (ttl) {
        await this.client.setex(id, ttl, sessStr);
      } else {
        await this.client.set(id, sessStr);
      }
    } catch (err) {
      console.error(err);
    }
  }

  /**
   * Delete session data from redis
   * @param {*} sid key
   */
  async destroy(sid) {
      const id= getSessionId(sid);
      await this.client.del(id)
  }
}

module.exports = RedisSessionStore

 

the above.  

 

Guess you like

Origin www.cnblogs.com/kongchuan/p/12205024.html