feat: 为 redis_bucket.go 添加限流日志
添加 trace-aware 日志: - Error: Redis 限流检查失败(fail-open 降级) - Warn: 限流触发,记录 key 和 retry_after_sec
This commit is contained in:
@@ -7,6 +7,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/hhs/camtalk/internal/config"
|
"github.com/hhs/camtalk/internal/config"
|
||||||
|
"github.com/hhs/camtalk/internal/trace"
|
||||||
"github.com/redis/go-redis/v9"
|
"github.com/redis/go-redis/v9"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -72,6 +73,7 @@ func NewRedisLimiter(client *redis.Client, cfg config.RateLimitConfig) *RedisLim
|
|||||||
|
|
||||||
// Allow 实现 Limiter 接口。
|
// Allow 实现 Limiter 接口。
|
||||||
func (l *RedisLimiter) Allow(ctx context.Context, key string) (bool, time.Duration) {
|
func (l *RedisLimiter) Allow(ctx context.Context, key string) (bool, time.Duration) {
|
||||||
|
log := trace.FromContext(ctx)
|
||||||
cfg := l.getBucketConfig(key)
|
cfg := l.getBucketConfig(key)
|
||||||
|
|
||||||
now := float64(time.Now().UnixNano()) / 1e9 // 秒,浮点
|
now := float64(time.Now().UnixNano()) / 1e9 // 秒,浮点
|
||||||
@@ -81,6 +83,7 @@ func (l *RedisLimiter) Allow(ctx context.Context, key string) (bool, time.Durati
|
|||||||
cfg.Capacity, cfg.Rate, now, ttl).Result()
|
cfg.Capacity, cfg.Rate, now, ttl).Result()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Errorw("rate limit check failed", "key", key, "error", err)
|
||||||
// Redis 错误时降级:允许请求(fail-open 策略)
|
// Redis 错误时降级:允许请求(fail-open 策略)
|
||||||
return true, 0
|
return true, 0
|
||||||
}
|
}
|
||||||
@@ -100,6 +103,7 @@ func (l *RedisLimiter) Allow(ctx context.Context, key string) (bool, time.Durati
|
|||||||
}
|
}
|
||||||
|
|
||||||
retryAfter := time.Duration(retryAfterSec*1000) * time.Millisecond
|
retryAfter := time.Duration(retryAfterSec*1000) * time.Millisecond
|
||||||
|
log.Warnw("rate limit triggered", "key", key, "retry_after_sec", retryAfterSec)
|
||||||
return false, retryAfter
|
return false, retryAfter
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user