package redis import ( "context" "fmt" "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 memory map[string]any } func New(dsn string, hashRadix string) *RedisClient { client, err := NewWithContext(context.Background(), dsn, hashRadix) if err != nil { panic(err) } return client } func NewWithContext(ctx context.Context, dsn string, hashRadix string) (*RedisClient, error) { if ctx == nil { ctx = context.Background() } arg, err := url.Parse(dsn) if err != nil { return nil, fmt.Errorf("parse redis dsn: %w", 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, err = strconv.Atoi(arg.Path) if err != nil { return nil, fmt.Errorf("parse redis db index: %w", err) } } //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(ctx).Result() if err != nil { _ = client.Close() return nil, fmt.Errorf("ping redis: %w", err) } return &RedisClient{ DB: db, Client: client, Ctx: ctx, memory: make(map[string]any), }, nil } func Hash(s string) int { if vars.RedisShardings <= 0 { return 0 } h := fnv.New32a() _, _ = h.Write([]byte(strings.ToLower(s))) return int(h.Sum32()) % vars.RedisShardings }