init
This commit is contained in:
64
cache/redis/redis.go
vendored
Normal file
64
cache/redis/redis.go
vendored
Normal file
@@ -0,0 +1,64 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"hash/fnv"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.apinb.com/bsm-sdk/core/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 string) *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(s string) int {
|
||||
h := fnv.New32a()
|
||||
h.Write([]byte(s))
|
||||
return int(h.Sum32()) % vars.RedisShardings
|
||||
}
|
||||
Reference in New Issue
Block a user