存储带有在redis中过期的前缀的密钥 [英] Storing keys with prefix that expire in redis

查看:43
本文介绍了存储带有在redis中过期的前缀的密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用键前缀存储过期 x 时间的值

Trying to store values that expire x amount of time with a key prefix

我正在使用 redis.我目前正在使用 hset

I'm using using redis. I'm currently storing the values using hset

import redis


r = redis.StrictRedis('localhost')


for i in range(10):
    r.hset('name', i, i)


print(r.hgetall('name'))

我希望每个密钥都有不同的过期时间,因为我将单独存储每个密钥.

I want each key to have a different expire time, as I will be storing each key individually.

我该怎么做?

推荐答案

这不能直接完成.您可以在整个 hset 上添加到期时间,但不能在单个字段上添加到期时间.如果你想这样做,你可以调用 r.expire('name', time),其中 time 是距离到期的秒数.

This can't be done directly. You can add an expiration on the hset as a whole, but not on individual fields. If you want to do this, you can call r.expire('name', time), where time is the number of seconds until expiration.

作为替代,您可以使用 set 而不是 hset:

As an alternative, you can use set instead of hset:

for i in range(10):
    r.set('name:' + str(i), i, ex=time_to_expire_s)

这将取消一些功能,因为(例如)您无法列出所有以name:"开头的键,但它可以让您独立设置键的到期时间.

This will take away some functionality, since (for example) you won't have a good way to list all keys that start with 'name:', but it will let you set expirations for keys independently.

作为第二个选项,您可以在 hset 的值中设置到期时间.这需要客户端逻辑,Redis 不会为你做任何清除;但你可以这样做:

As a second option, you can set expirations in the values of the hset. This requires client side logic, and Redis won't do any expunging for you; but you could do something like:

for i in range(10):
    r.hset(
        'name',
        i,
        json.dumps({ 'value': i, 'expiration': time.time() + time_to_expire_s })
    )

然后如果你读过一个过期时间在过去的值,你会认为这是一个缓存未命中.如果您试图使密钥过期以释放内存,这对您无济于事,但如果您的目标是使密钥因某种正确性原因过期,这可能对您有用.

And then if you ever read a value whose expiration is in the past, you consider that to be a cache miss. This won't help you if you're trying to expire keys in order to free memory, but if your goal is to have the keys expire for some sort of correctness reason, this might work for you.

这篇关于存储带有在redis中过期的前缀的密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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