Files
core/cache/redis/redis.go

88 lines
1.6 KiB
Go
Raw Normal View History

2025-02-07 13:01:38 +08:00
package redis
import (
"context"
2026-06-20 23:29:58 +08:00
"fmt"
2025-02-07 13:01:38 +08:00
"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
2025-10-02 18:06:23 +08:00
memory map[string]any
2025-02-07 13:01:38 +08:00
}
func New(dsn string, hashRadix string) *RedisClient {
2026-06-20 23:29:58 +08:00
client, err := NewWithContext(context.Background(), dsn, hashRadix)
2025-02-07 13:01:38 +08:00
if err != nil {
panic(err)
}
2026-06-20 23:29:58 +08:00
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)
}
2025-02-07 13:01:38 +08:00
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 {
2026-06-20 23:29:58 +08:00
db, err = strconv.Atoi(arg.Path)
if err != nil {
return nil, fmt.Errorf("parse redis db index: %w", err)
}
2025-02-07 13:01:38 +08:00
}
//connect redis server
client := cacheRedis.NewClient(&cacheRedis.Options{
Addr: arg.Host,
Password: pwd, // no password set
DB: db, // use default DB
Protocol: 3,
})
2026-06-20 23:29:58 +08:00
_, err = client.Ping(ctx).Result()
2025-02-07 13:01:38 +08:00
if err != nil {
2026-06-20 23:29:58 +08:00
_ = client.Close()
return nil, fmt.Errorf("ping redis: %w", err)
2025-02-07 13:01:38 +08:00
}
return &RedisClient{
DB: db,
Client: client,
2026-06-20 23:29:58 +08:00
Ctx: ctx,
2025-10-02 18:06:23 +08:00
memory: make(map[string]any),
2026-06-20 23:29:58 +08:00
}, nil
2025-02-07 13:01:38 +08:00
}
func Hash(s string) int {
2026-06-20 23:29:58 +08:00
if vars.RedisShardings <= 0 {
return 0
}
2025-02-07 13:01:38 +08:00
h := fnv.New32a()
2026-06-20 23:29:58 +08:00
_, _ = h.Write([]byte(strings.ToLower(s)))
2025-02-07 13:01:38 +08:00
return int(h.Sum32()) % vars.RedisShardings
}