62 lines
1.0 KiB
Go
62 lines
1.0 KiB
Go
package redis
|
|
|
|
import (
|
|
"context"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"git.apinb.com/bsm-sdk/engine/vars"
|
|
cacheRedis "github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
const (
|
|
Nil = cacheRedis.Nil
|
|
)
|
|
|
|
// RedisClient .
|
|
type RedisClient struct {
|
|
DB int
|
|
Client *cacheRedis.Client
|
|
Ctx context.Context
|
|
}
|
|
|
|
func New(dsn string, hashRadix int) *RedisClient {
|
|
arg, err := url.Parse(dsn)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
pwd, _ := arg.User.Password()
|
|
|
|
//get db number,default:0
|
|
var db int = 0
|
|
arg.Path = strings.ReplaceAll(arg.Path, "/", "")
|
|
if arg.Path == "" {
|
|
db = Hash(hashRadix)
|
|
} else {
|
|
db, _ = strconv.Atoi(arg.Path)
|
|
}
|
|
|
|
//connect redis server
|
|
client := cacheRedis.NewClient(&cacheRedis.Options{
|
|
Addr: arg.Host,
|
|
Password: pwd, // no password set
|
|
DB: db, // use default DB
|
|
Protocol: 3,
|
|
})
|
|
_, err = client.Ping(context.Background()).Result()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
return &RedisClient{
|
|
DB: db,
|
|
Client: client,
|
|
Ctx: context.Background(),
|
|
}
|
|
}
|
|
|
|
func Hash(i int) int {
|
|
return i % vars.RedisShardings
|
|
}
|