Storing keys with prefix that expire in redis

2020-04-06 03:15发布

问题:

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

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.

How do I do this?

回答1:

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.

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)

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.

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.



标签: python redis