kotlincachingredisttl

Is it possible to define relative ttl in Redis cache?


I have define 10 mins time-to-live(ttl) for my cache.So it will expire after 10 mins. Is there any way to define the relative ttl, like it will expire after 10 mins of the last using time. If yes, how to define that in a kotlin/java spring boot project. example:- if the cache is set at 10:00 am and last time the cache is used at 10:08 am, then I want the cache to expire at 10:18 am.


Solution

  • Redis itself supports this for keys holding string values using the GETEX command (https://redis.io/commands/getex/).

    This gets the value stored at a key and sets the TTL atomically. Combine this with the SET command with the EX option when first storing or updating the data... all times are in seconds.

    Let's store a value with a 20 second time to live, then update that back to a new 20 seconds each time we get the value out of Redis:

    127.0.0.1:6379> set mycachedvalue hello ex 20
    OK
    127.0.0.1:6379> ttl mycachedvalue
    (integer) 15
    127.0.0.1:6379> getex mycachedvalue ex 20
    "hello"
    127.0.0.1:6379> ttl mycachedvalue
    (integer) 18
    

    For Kotlin, you'll need to work out how your Redis client uses these commands and call them appropriately.