2025-09-12 17:12:02 +08:00
|
|
|
// Package util provide some utility functions
|
2025-03-25 17:00:09 +08:00
|
|
|
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
|
|
|
|
|
}
|