Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing keys with prefix that expire in redis

Tags:

python

redis

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?

like image 500
nadermx Avatar asked Mar 15 '16 01:03

nadermx


People also ask

Does Redis return expired keys?

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.

How can I get Redis key expiry?

Redis TTL command is used to get the remaining time of the key expiry in seconds.

Can you define an expiration time of a field in a hash Redis?

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.

How do I change the expiration date on Redis cache?

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.


1 Answers

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.

like image 97
sasmith Avatar answered Oct 03 '22 00:10

sasmith