package util import ( "context" "fmt" "github.com/redis/go-redis/v9" ) // NewRedisClient define func of initialize the Redis client func NewRedisClient(addr string, opts ...RedisOption) (*redis.Client, error) { // default options options := RedisOptions{ redisOptions: &redis.Options{ Addr: addr, }, } // Apply configuration options from config for _, opt := range opts { opt(&options) } // create redis client client := redis.NewClient(options.redisOptions) if options.timeout > 0 { // check if the connection is successful ctx, cancel := context.WithTimeout(context.Background(), options.timeout) defer cancel() if err := client.Ping(ctx).Err(); err != nil { return nil, fmt.Errorf("can not connect redis:%v", err) } } return client, nil }