优化缓存结构,优化缓存机制
This commit is contained in:
Vendored
+61
-2
@@ -2,6 +2,7 @@ package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
@@ -9,7 +10,7 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
curveLockTTL = 10 * time.Second
|
||||
curveLockTTL = 10 * time.Second
|
||||
curveLockRetryDelay = 100 * time.Millisecond
|
||||
curveLockMaxRetries = 50
|
||||
)
|
||||
@@ -42,6 +43,64 @@ func (c *CurveCache) Set(ctx context.Context, brand, name, target, data string)
|
||||
return c.rdb.HSet(ctx, key, target, data).Err()
|
||||
}
|
||||
|
||||
// GetFR 直接获取独立存储的 fr 数据(用于 modelCurve 接口)
|
||||
func (c *CurveCache) GetFR(ctx context.Context, brand, name string) (string, error) {
|
||||
key := brand + " " + name
|
||||
val, err := c.rdb.HGet(ctx, key, "__fr").Result()
|
||||
if err == redis.Nil {
|
||||
return "", nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("hget curve fr: %w", err)
|
||||
}
|
||||
return val, nil
|
||||
}
|
||||
|
||||
// GetWithFR 获取 target 缓存数据并合并独立存储的 fr 数据
|
||||
// 兼容旧缓存:若 target 数据中已有 fr 字段则直接返回
|
||||
func (c *CurveCache) GetWithFR(ctx context.Context, brand, name, target string) (string, error) {
|
||||
key := brand + " " + name
|
||||
|
||||
targetData, err := c.rdb.HGet(ctx, key, target).Result()
|
||||
if err == redis.Nil {
|
||||
return "", nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("hget curve target: %w", err)
|
||||
}
|
||||
if targetData == "" {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// 旧缓存兼容:已有 fr 字段无需合并
|
||||
var check map[string]json.RawMessage
|
||||
if err := json.Unmarshal([]byte(targetData), &check); err == nil {
|
||||
if _, hasFR := check["fr"]; hasFR {
|
||||
return targetData, nil
|
||||
}
|
||||
}
|
||||
|
||||
// 新缓存:从 __fr 字段读取 fr 数据并合并
|
||||
frData, err := c.rdb.HGet(ctx, key, "__fr").Result()
|
||||
if err == redis.Nil || frData == "" {
|
||||
return targetData, nil
|
||||
}
|
||||
if err != nil {
|
||||
return targetData, nil
|
||||
}
|
||||
|
||||
var result map[string]json.RawMessage
|
||||
if err := json.Unmarshal([]byte(targetData), &result); err != nil {
|
||||
return targetData, nil
|
||||
}
|
||||
result["fr"] = json.RawMessage(frData)
|
||||
merged, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return targetData, nil
|
||||
}
|
||||
return string(merged), nil
|
||||
}
|
||||
|
||||
// AcquireLock 获取分布式锁(SETNX),防止并发请求同一个曲线数据
|
||||
func (c *CurveCache) AcquireLock(ctx context.Context, brand, name, target string) (bool, error) {
|
||||
lockKey := brand + " " + name + ":" + target + ":lock"
|
||||
@@ -85,4 +144,4 @@ func (c *CurveCache) GetWithLock(ctx context.Context, brand, name, target string
|
||||
|
||||
// 未获取锁,等待后重试
|
||||
return "", false, nil
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user