In an application, you may want to store temporary data like session information, cached data, or real-time metrics in Redis. To avoid the data staying in Redis indefinitely, we can set a time-to-live (TTL) for these keys which automatically removes them after a certain period.
package main import ( "github.com/go-redis/redis" "time" ) func main() { client := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password set DB: 0, // use default DB }) err := client.Set("key", "value", 10*time.Second).Err() if err != nil { panic(err) } }
In this example, 10*time.Second
sets the TTL for 'key' to 10 seconds.
package main import ( "github.com/go-redis/redis" "time" ) func main() { client := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password set DB: 0, // use default DB }) _, err := client.Do("SET", "key", "value").Result() if err != nil { panic(err) } err = client.Expire("key", 10*time.Second).Err() if err != nil { panic(err) } }
In this example, Expire
method is used to set the TTL for 'key' to 10 seconds.
Remember to handle errors properly in your production code. Also, be careful with the TTL values; setting them too short might cause data to disappear before it's used, setting them too long can consume more memory than necessary.
Setting data without a proper TTL where it's required can cause the Redis instance to run out of memory. Misunderstanding the TTL as milliseconds instead of seconds is also a common mistake.
Q: Can I view the remaining TTL of a key?
A: Yes. You can use the TTL
function: timeLeft, err := client.TTL("key").Result()
to get the remaining time-to-live (in seconds) for the specified key.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.