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?
Normally Redis keys are created without an associated time to live. The key will simply live forever, unless it is removed by the user in an explicit way, for instance using the DEL command.
Redis TTL command is used to get the remaining time of the key expiry in seconds.
Redis provide key-level expiration only, and nested element expiration (i.e. fields in Hashes, members in Sets, etc...) is not supported. Put differently, you can't expire individual fields in a Hash.
First, create a key in Redis and set some value in it. Now, set timeout of the previously created key. In the above example, 1 minute (or 60 seconds) time is set for the key tutorialspoint. After 1 minute, the key will expire automatically.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With