Quantcast
Channel: How to "EXPIRE" the "HSET" child key in redis? - Stack Overflow
Viewing all articles
Browse latest Browse all 19

Answer by rococo for How to "EXPIRE" the "HSET" child key in redis?

$
0
0

If your use-case is that you're caching values in Redis and are tolerant of stale values but would like to refresh them occasionally so that they don't get too stale, a hacky workaround is to just include a timestamp in the field value and handle expirations in whatever place you're accessing the value.

This allows you to keep using Redis hashes normally without needing to worry about any complications that might arise from the other approaches. The only cost is a bit of extra logic and parsing on the client end. Not a perfect solution, but it's what I typically do as I haven't needed TTL for any other reason and I'm usually needing to do extra parsing on the cached value anyways.

So basically it'll be something like this:

In Redis:

hash_name- field_1: "2021-01-15;123"- field_2: "2021-01-20;125"- field_2: "2021-02-01;127"

Your (pseudo)code:

val = redis.hget(hash_name, field_1)timestamp = val.substring(0, val.index_of(";"))if now() > timestamp:  new_val = get_updated_value()  new_timestamp = now() + EXPIRY_LENGTH  redis.hset(hash_name, field_1, new_timestamp +";" + new_val)  val = new_valelse:  val = val.substring(val.index_of(";"))// proceed to use val

The biggest caveat imo is that you don't ever remove fields so the hash can grow quite large. Not sure there's an elegant solution for that - I usually just delete the hash every once in a while if it feels too big. Maybe you could keep track of everything you've stored somewhere and remove them periodically (though at that point, you might as well just be using that mechanism to expire the fields manually...).


Viewing all articles
Browse latest Browse all 19

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>