Redis、会话过期和反向查找 [英] Redis, session expiration, and reverse lookup

查看:39
本文介绍了Redis、会话过期和反向查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在构建一个网络应用程序,并希望使用 Redis 来存储会话.在登录时,会话将插入到具有相应用户 ID 的 Redis 中,并将过期时间设置为 15 分钟.我现在想实现会话的反向查找(获取具有特定用户 ID 的会话).这里的问题是,由于我无法搜索 Redis 键空间,如何实现这一点.一种方法是为每个用户 ID 设置一个 redis,包含所有会话 ID.但是由于 Redis 不允许集合中的项目过期,并且会话设置为过期,因此集合中将有大量不存在的会话 ID.

I'm currently bulding a web app and would like to use Redis to store sessions. At login, the session is inserted into Redis with a corresponding user id, and expiration set at 15 minutes. I would now like to implement reverse look-up for sessions (get sessions with a certain user id). The problem here is, since I can't search the Redis keyspace, how to implement this. One way would be to have a redis set for each userId, containing all session ids. But since Redis doesn't allow expiration of an item in a set, and sessions are set to expire, there would be a ton of inexistent session ids in the sets.

在密钥到期时从集合中删除 id 的最佳方法是什么?或者,有没有更好的方法来完成我想要的(反向查找)?

What would be the best way to remove ids from sets on key expiration? Or, is there a better way of accomplishing what I want (reverse look-up)?

推荐答案

Redis (2.6) 的当前发布分支上,您无法在项目过期时收到通知.它可能会随着下一个版本而改变.

On the current release branch of Redis (2.6), you cannot have notifications when items are expired. It will probably change with the next versions.

同时,为了支持您的需求,您需要手动实现到期通知支持.所以你有:

In the meantime, to support your requirement, you need to manually implement expiration notification support. So you have:

session:<sessionid> -> a hash storing your session data - one of the field is <userid>
user:<userid> -> a set of <sessionid>

当会话过期时,您需要从用户集中删除 sessionid.所以你可以维护一个额外的排序集,它的分数是一个时间戳.

You need to remove sessionid from the user set when the session expires. So you can maintain a additional sorted set whose score is a timestamp.

当您为用户 100 创建会话 10 时:

When you create session 10 for user 100:

MULTI
HMSET session:10 userid:100 ... other session data ...
SADD user:100 10
ZADD to_be_expired <current timestamp + session timeout> 10
EXEC

然后,您需要构建一个守护进程,它将轮询 zset 以识别要过期的会话(ZRANGEBYSCORE).对于每个过期的会话,它必须维护数据结构:

Then, you need to build a daemon which will poll the zset to identify the session to expire (ZRANGEBYSCORE). For each expired session, it has to maintain the data structure:

主要的困难是确保守护进程轮询和处理项目时没有竞争条件.请参阅我对这个问题的回答以了解如何实施:

The main difficulty is to ensure there is no race conditions when the daemon polls and processes the items. See my answer to this question to see how it can be implemented:

如何基于redis处理会话过期?

这篇关于Redis、会话过期和反向查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆