You will learn how to set expiration times on your Redis keys. This is useful for many situations, such as caching data, managing session lifetimes, or any scenario where you want data to automatically expire after a certain period. We will learn how to set expiration times on keys and check the remaining time-to-live (TTL) for a key.
Here's a quick preview of what you will be doing:
To set a key with an expiration time, you can use the Set method with an additional parameter for timestamp:
package main
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
func main() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
key := "session:12345"
ctx := context.Background()
// Set the key with a value and an expiration time of 2 seconds
err := client.Set(ctx, key, "data", 2*time.Second).Err()
if err != nil {
panic(err) // Handle any errors in setting the key
}
// Retrieve and print the time-to-live (TTL) for the key
ttl, err := client.TTL(ctx, key).Result()
if err != nil {
panic(err) // Handle any errors in getting the TTL
}
fmt.Printf("Time-to-live for session key: %v\n", ttl)
// Wait for the key to potentially expire
time.Sleep(3 * time.Second)
// Attempt to retrieve the value of the key after expiration time
value, err := client.Get(ctx, key).Result()
if err == redis.Nil {
fmt.Println("Value: None") // The key has expired as expected
} else if err != nil {
panic(err) // Handle any errors in retrieving the key
} else {
fmt.Printf("Value: %s\n", value) // Print the value if the key hasn't expired
}
}
The above code snippet shows how to set a key (session:12345) with a value (data) that expires after 2 seconds.
To check the remaining time-to-live (TTL) for a key, you can use the TTL method with the key name as the parameter.
After waiting for the expiration time, you can verify that the key no longer exists. This code waits 3 seconds and then attempts to get the value of the key, which should indicate that the key has expired.
Another useful method is Expire, which allows you to set the expiration time for a key after it has been created:
package main
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
func main() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
key := "session:12345"
ctx := context.Background()
// Set the key with a value and no expiration initially
err := client.Set(ctx, key, "data", 0).Err() // 0 indicates no expiration for now
if err != nil {
panic(err) // Handle any errors in setting the key
}
// Set an expiration time of 2 seconds for the key
err = client.Expire(ctx, key, 2*time.Second).Err()
if err != nil {
panic(err) // Handle any errors in setting expiration
}
// Retrieve and print the time-to-live (TTL) for the key
ttl, err := client.TTL(ctx, key).Result()
if err != nil {
panic(err) // Handle any errors in getting the TTL
}
fmt.Printf("Time-to-live for the key: %v\n", ttl)
// Wait for the key to potentially expire
time.Sleep(3 * time.Second)
// Attempt to retrieve the value of the key after expiration time
value, err := client.Get(ctx, key).Result()
if err == redis.Nil {
fmt.Println("Value: None") // The key has expired as expected
} else if err != nil {
panic(err) // Handle any errors in retrieving the key
} else {
fmt.Printf("Value: %s\n", value) // Print the value if the key hasn't expired
}
}
This code snippet sets the key session:12345 with a value (data) and then sets the expiration time to 2 seconds. We will explore this method in more detail in the practice section.