Egg: 如何获取存在redis中的所有在线session

Created on 30 Apr 2019  ·  5Comments  ·  Source: eggjs/egg

使用session-redis插件将登陆用户的session保存到了redis中

在中间件中判断用户是否登陆 使用了ctx.session都能获取到。

redis中查看 session的key 皆是例如
1556586279490-oeInrL6FYVfjfVRa1ZJKJP_Qv51nVVEc
这样的。

我想限制账号重复登陆,如果获取到已经登陆的所有session,然后判断下是否已经登陆
如果登陆了,就把旧的session失效掉。

请问 如何获取。
谢谢

Most helpful comment

通过 options.genid() 来定制化自己的 key,就可以实现你的需求了,例如将 key 定制化成与 user_id 相关的。

All 5 comments

通过 options.genid() 来定制化自己的 key,就可以实现你的需求了,例如将 key 定制化成与 user_id 相关的。

@superglg738 你应该在数据库记录一个用户最近的登录 session id,如果真的要注销已经登录的 session,那么就可以查询这个表来操作,然后使用 redis store 将这些 session id 数据清理。

非常感谢大大们的解释。

通过配置default.js 的genid,统一定义登录的session为 session:uuid.v4() ,后续就取到了。

现在考虑的是session被踢出去后,给前台发送相应的事件。

@dead-horse 怎么在 genid() 里获取到 user_id? ctx.session 和 key 在获取到 user_id 之前就已经生成

@dead-horse user_id 是在登录后才拿到的,我不得不重新调用initFromExternal:

this.ctx.session_user_id = user_id; // 保存 user_id 到 ctx 对象中,在 genid(ctx) 使用
await this.ctx.session._sessCtx.initFromExternal();

this.ctx.session.user = {
  user_id,
  name: 'username',
};
Was this page helpful?
0 / 5 - 0 ratings

Related issues

fengmk2 picture fengmk2  ·  51Comments

shaoshuai0102 picture shaoshuai0102  ·  52Comments

andylei18 picture andylei18  ·  35Comments

popomore picture popomore  ·  38Comments

popomore picture popomore  ·  70Comments