go-redis / cache

Cache library with Redis backend for Golang
https://redis.uptrace.dev/guide/go-redis-cache.html
BSD 2-Clause "Simplified" License
756 stars 95 forks source link

Feature request: Support TTL command #75

Open me0den opened 3 years ago

me0den commented 3 years ago

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 3 years ago

Can we support this command for more flexible TTL values?

Could you explain what you mean by this?

me0den commented 3 years ago

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 3 years ago

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.

tausten commented 2 years ago

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.