fix logger,cache

This commit is contained in:
2025-10-02 18:06:23 +08:00
parent 10ee9bba10
commit f934472e50
9 changed files with 869 additions and 12 deletions

82
cache/redis/cache.go vendored Normal file
View File

@@ -0,0 +1,82 @@
package redis
import (
"encoding/json"
"fmt"
"time"
"git.apinb.com/bsm-sdk/core/errcode"
)
const (
// 缓存键前缀
CacheKeyPrefix = "bsm:"
// 缓存过期时间
DefaultTTL = 30 * time.Minute // 30分钟
)
// buildKey 构建缓存键
func (c *RedisClient) buildKey(prefix string, params ...interface{}) string {
key := CacheKeyPrefix + prefix
for _, param := range params {
key += fmt.Sprintf(":%v", param)
}
return key
}
// Get 获取缓存
func (c *RedisClient) Get(key string, result interface{}) error {
if c.Client == nil {
return errcode.ErrRedis
}
data, err := c.Client.Get(c.Ctx, key).Result()
if err != nil {
return errcode.NewError(500, err.Error())
}
return json.Unmarshal([]byte(data), result)
}
// Set 设置缓存
func (c *RedisClient) Set(key string, value interface{}, ttl time.Duration) error {
if c.Client == nil {
return errcode.ErrRedis
}
data, err := json.Marshal(value)
if err != nil {
return errcode.NewError(500, err.Error())
}
return c.Client.Set(c.Ctx, key, data, ttl).Err()
}
// Delete 删除缓存
func (c *RedisClient) Delete(key string) error {
if c.Client == nil {
return errcode.ErrRedis
}
return c.Client.Del(c.Ctx, key).Err()
}
// ClearAllCache 清除所有缓存
func (c *RedisClient) ClearAllCache() error {
if c.Client == nil {
return errcode.ErrRedis
}
pattern := CacheKeyPrefix + "*"
keys, err := c.Client.Keys(c.Ctx, pattern).Result()
if err != nil {
return errcode.NewError(500, err.Error())
}
if len(keys) > 0 {
return c.Client.Del(c.Ctx, keys...).Err()
}
return nil
}

View File

@@ -20,6 +20,7 @@ type RedisClient struct {
DB int
Client *cacheRedis.Client
Ctx context.Context
memory map[string]any
}
func New(dsn string, hashRadix string) *RedisClient {
@@ -54,6 +55,7 @@ func New(dsn string, hashRadix string) *RedisClient {
DB: db,
Client: client,
Ctx: context.Background(),
memory: make(map[string]any),
}
}