58 lines
1.1 KiB
Go
58 lines
1.1 KiB
Go
package redis
|
|
|
|
import (
|
|
commonConfig "common/config"
|
|
"context"
|
|
"crypto/tls"
|
|
"errors"
|
|
"fmt"
|
|
"github.com/redis/go-redis/v9"
|
|
"time"
|
|
)
|
|
|
|
var (
|
|
redisClient *redis.Client
|
|
redisNotInitErr = errors.New("redis is not initialized.")
|
|
keyNotExist = errors.New("key does not exist")
|
|
Nil = redis.Nil
|
|
)
|
|
|
|
func Init(cfg *commonConfig.RedisConfig) error {
|
|
url := fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)
|
|
if cfg.Tls {
|
|
redisClient = redis.NewClient(&redis.Options{
|
|
Addr: url,
|
|
Password: cfg.Auth,
|
|
DB: cfg.Db,
|
|
DialTimeout: 20 * time.Second,
|
|
Username: cfg.UserName,
|
|
TLSConfig: &tls.Config{},
|
|
})
|
|
} else {
|
|
redisClient = redis.NewClient(&redis.Options{
|
|
Addr: url,
|
|
Password: cfg.Auth,
|
|
DB: cfg.Db,
|
|
DialTimeout: 20 * time.Second,
|
|
})
|
|
}
|
|
|
|
ret := redisClient.Ping(context.Background())
|
|
//p := redisClient.Pipeline()
|
|
//l := p.HGetAll(xxx, xxx)
|
|
//s := p.Get(xxx, xx)
|
|
//p.Exec(xxx)
|
|
return ret.Err()
|
|
}
|
|
|
|
func Close() error {
|
|
if redisClient != nil {
|
|
return redisClient.Close()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func GetRedisClient() *redis.Client {
|
|
return redisClient
|
|
}
|