perf(service): 移除 jitter 随机数全局锁

This commit is contained in:
yangjianbo
2026-02-06 21:20:25 +08:00
parent 028f8aaa97
commit c4182f8c33

View File

@@ -6,8 +6,7 @@ import (
"encoding/hex" "encoding/hex"
"errors" "errors"
"fmt" "fmt"
"math/rand" "math/rand/v2"
"sync"
"time" "time"
"github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/config"
@@ -24,9 +23,8 @@ type apiKeyAuthCacheConfig struct {
} }
var ( var (
jitterRandMu sync.Mutex // 认证缓存抖动直接使用 rand/v2 的顶层函数。
// 认证缓存抖动使用独立随机源,避免全局 Seed // rand/v2 顶层函数并发安全,避免全局互斥锁成为热点。
jitterRand = rand.New(rand.NewSource(time.Now().UnixNano()))
) )
func newAPIKeyAuthCacheConfig(cfg *config.Config) apiKeyAuthCacheConfig { func newAPIKeyAuthCacheConfig(cfg *config.Config) apiKeyAuthCacheConfig {
@@ -68,9 +66,7 @@ func (c apiKeyAuthCacheConfig) jitterTTL(ttl time.Duration) time.Duration {
percent = 100 percent = 100
} }
delta := float64(percent) / 100 delta := float64(percent) / 100
jitterRandMu.Lock() randVal := rand.Float64()
randVal := jitterRand.Float64()
jitterRandMu.Unlock()
factor := 1 - delta + randVal*(2*delta) factor := 1 - delta + randVal*(2*delta)
if factor <= 0 { if factor <= 0 {
return ttl return ttl