There are three ways to set cache expiration policy in Golang applications: use time.Duration: set a fixed expiration time. Use expiration timestamp: Explicitly specify the expiration time. Use a custom expiration policy: flexibly set the expiration time through redis.HookFunc.
Using caching in Golang applications can significantly improve performance. However, there is a time limit for the existence of cached items, and they need to be invalidated after this limit is exceeded. Here's how to set cache expiration policy in Golang:
The easiest way is to use the time.Duration
type, which represents a time span. For example:
import ( "context" "time" "github.com/go-redis/redis/v8" ) func main() { ctx := context.Background() client := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) // 设置缓存值,过期时间为 10 分钟 err := client.SetEX(ctx, "my-key", "my-value", 10*time.Minute).Err() if err != nil { panic(err) } }
Another approach is to use expiration timestamp, which is a Unix timestamp that indicates when the cache item expires. For example:
import ( "context" "time" "github.com/go-redis/redis/v8" ) func main() { ctx := context.Background() client := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) // 设置缓存值,到期时间戳为 10 分钟后的时间 expiration := time.Now().Add(10 * time.Minute).Unix() err := client.Set(ctx, "my-key", "my-value", time.Duration(expiration-time.Now().Unix())*time.Second).Err() if err != nil { panic(err) } }
If you need a more complex expiration strategy, you can use redis.HookFunc
. For example, you can set a custom expiration time based on cache item usage:
import ( "context" "time" "github.com/go-redis/redis/v8" ) func main() { ctx := context.Background() client := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) // 设置自定义过期策略 client.AddHook(redis.AfterSetHookFunc(func(ctx context.Context, key string, value interface{}) { // 根据缓存项的使用情况计算到期时间 expiration := calculateExpiration(key, value) // 设置到期时间戳 client.Expire(ctx, key, time.Duration(expiration-time.Now().Unix())*time.Second) })) }
The above is the detailed content of How to set cache expiration policy in Golang application?. For more information, please follow other related articles on the PHP Chinese website!