go-redis/cache

Feature request: Support TTL command

me0den opened this issue · 4 comments

Hi guys,

In my scenario, I have set a TTL value for the redis key and reuse it for next time. Can we support this command for more flexible TTL values?

ttl, _ := redis.TTL(ctx, key).Result()
redis.Set(ctx, key, val, ttl).Result()
knadh commented

Can we support this command for more flexible TTL values?

Could you explain what you mean by this?

For each key in Redis, We have set a TTL value for it. I want to get this TTL value and reuse it for the next time set. Sorry if my eng is bad.

For code example:

// Set ttl 3 mins for key
ttl := 3 * time.Minute
redis.Set(ctx, key, val, ttl).Result()

// after a momemt
ttl, _ := redis.TTL(ctx, key).Result()

// re-set ttl to key
redis.Set(ctx, key, val, ttl).Result()
knadh commented

Your example is the right way of doing this (you should handle those errors though). If you are doing this in many places, you could just wrap it in a helper function SetWithOldTTL(key, val, cache ...). Don't think such a function in the main lib would be ideal.

Heads-up -- in recent versions of https://github.com/go-redis/redis , there is a redis.KeepTTL value (i.e. -1) which maps to the REDIS keepttl option for write operations, but the latest version of cache takes anything < 0 and remaps it to 0, so this doesn't flow through to the underlying redis client, and ultimately doesn't turn into keepttl on the Redis server.