Redis:为Set中的键值对设置超时 [英] Redis: To set timeout for a key value pair in Set

查看:92
本文介绍了Redis:为Set中的键值对设置超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Redis 设置,键为 'a',值为 '1'、'2'、'3'.有没有办法为集合中的每个键值对设置不同的过期时间.

I have a Redis set with key 'a' and value '1','2','3'. Is there a way to set different expire time for each key-value pair in the set.

例如 ('a','1') 应在 60 秒后过期,而 ('a','2') 应在 120 秒后过期.

For example ('a','1') should expire after 60 seconds where as ('a','2') should expire after 120 seconds.

推荐答案

很遗憾,没有.Redis 的容器"(即列表、散列、集合和排序集合)不支持每个成员过期,尽管过去多次请求此功能.

Unfortunately, no. Redis' "containers" (i.e. lists, hashes, sets and sorted sets) do not support per-member expiry, although this functionality has been requested many times in the past.

但是,您可以实现自己的逻辑来实现该结果.有几种可能的方法来解决这个问题 - 这是一个例子.不使用集合,而是使用排序集合 (ZSET),并使用纪元值将每个成员的分数设置为其到期时间.例如,这种类型的工作流可以使用 Lua 脚本来实现.要添加成员,请使用以下内容:

You can, however, implement your own logic to achieve that result. There are several possible approaches to address this - here's one example. Instead of using a set, use a sorted set (ZSET) and set each member's score to its expiry time using epoch values. This type of workflow could be implemented using a Lua script for example. To add members use something like:

redis.call('zadd', KEYS[1], os.time()+ARGV[1], ARGV[2])

并根据您的示例使用1 a 60 1"和1 a 120 2"作为参数对其进行评估.要真正使集合中的项目过期",您需要在它们的时间过去后将其删除.您可以通过实施定期扫描您的列表或访问它来做到这一点.例如,可以使用以下 Lua 使成员过期:

and EVAL it using '1 a 60 1' and '1 a 120 2' as arguments, per your example. To actually "expire" the items from the set, you'll need to delete them once their time has passed. You can do that either by implementing a periodical process that scans your list or upon accessing it. For example, the following Lua can be used to expire members:

redis.call('zremrangebyscore', KEYS[1], '-inf', os.time())

并根据您的示例使用1 a"作为参数对其进行评估.

and EVAL it using '1 a' as arguments per your example.

如何使用 Python 实现上述目标

How to achieve the above using Python

import time
import redis

def add(r, key, ttl, member):
    r.zadd(key, member, int(time.time()+ttl))

def expire(r, key):
    r.zremrangebyscore(key, '-inf', int(time.time()))

...

r = redis.Redis()
add(r, 'a', 1, 60)
add(r, 'a', 2, 120)

# periodically or before every operation do
expire(r, 'a')

这篇关于Redis:为Set中的键值对设置超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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