Pattern: Navigation session
模式:导航会话
Imagine you have a web service and you are interested in the latest N pages recently visited by your users, such that each adjacent page view was not performed more than 60 seconds after the previous. Conceptually you may think at this set of page views as a Navigation session if your user, that may contain interesting information about what kind of products he or she is looking for currently, so that you can recommend related products.
You can easily model this pattern in Redis using the following strategy: every time the user does a page view you call the following commands:
假设你有一项 web 服务,打算根据用户最近访问的 N 个页面来进行物品推荐,并且假设用户停止阅览超过 60 秒,那么就清空阅览记录(为了减少物品推荐的计算量,并且保持推荐物品的新鲜度)。
这些最近访问的页面记录,我们称之为『导航会话』(Navigation session),可以用 INCR 和 RPUSH 命令在 Redis 中实现它:每当用户阅览一个网页的时候,执行以下代码:
MULTI
RPUSH pagewviews.user: http://.....
EXPIRE pagewviews.user: 60
EXEC
If the user will be idle more than 60 seconds, the key will be deleted and only subsequent page views that have less than 60 seconds of difference will be recorded.
This pattern is easily modified to use counters using INCR instead of lists using RPUSH.
如果用户停止阅览超过 60 秒,那么它的导航会话就会被清空,当用户重新开始阅览的时候,系统又会重新记录导航会话,继续进行物品推荐。
参考:http://www.redis.io/commands/expire
http://redis.readthedocs.org/en/latest/key/expire.html