codex optz.

This commit is contained in:
2026-06-20 23:29:58 +08:00
parent 40afc6c0d5
commit ebed85772f
11 changed files with 282 additions and 422 deletions

35
cache/redis/redis.go vendored
View File

@@ -2,6 +2,7 @@ package redis
import (
"context"
"fmt"
"hash/fnv"
"net/url"
"strconv"
@@ -24,10 +25,22 @@ type RedisClient struct {
}
func New(dsn string, hashRadix string) *RedisClient {
arg, err := url.Parse(dsn)
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
@@ -36,7 +49,10 @@ func New(dsn string, hashRadix string) *RedisClient {
if arg.Path == "" {
db = Hash(hashRadix)
} else {
db, _ = strconv.Atoi(arg.Path)
db, err = strconv.Atoi(arg.Path)
if err != nil {
return nil, fmt.Errorf("parse redis db index: %w", err)
}
}
//connect redis server
@@ -46,21 +62,26 @@ func New(dsn string, hashRadix string) *RedisClient {
DB: db, // use default DB
Protocol: 3,
})
_, err = client.Ping(context.Background()).Result()
_, err = client.Ping(ctx).Result()
if err != nil {
panic(err)
_ = client.Close()
return nil, fmt.Errorf("ping redis: %w", err)
}
return &RedisClient{
DB: db,
Client: client,
Ctx: context.Background(),
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)))
_, _ = h.Write([]byte(strings.ToLower(s)))
return int(h.Sum32()) % vars.RedisShardings
}