feat: 实现内存令牌桶限流器
- Limiter 接口定义(Allow + Stop 方法) - TokenBucket 实现(容量、填充速率、并发安全) - MemoryLimiter 管理多用户令牌桶 - 后台 goroutine 定期清理不活跃桶(10 分钟) - 完整单元测试覆盖(11 个测试用例,全部通过) - 边界情况处理(rate=0、capacity=0、并发安全)
This commit is contained in:
17
backend/internal/ratelimit/limiter.go
Normal file
17
backend/internal/ratelimit/limiter.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package ratelimit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Limiter 速率限制器接口。
|
||||
type Limiter interface {
|
||||
// Allow 判断 key 是否允许执行一次操作。
|
||||
// key 通常为 "userID:action" 格式。
|
||||
// 返回 (allowed, retryAfter)。retryAfter 表示需要等待的时间。
|
||||
Allow(ctx context.Context, key string) (bool, time.Duration)
|
||||
|
||||
// Stop 停止限流器,清理资源(如后台 goroutine)。
|
||||
Stop()
|
||||
}
|
||||
Reference in New Issue
Block a user