2 Star 0 Fork 0

TeamsHub/backend-gopkg

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
tpslimiter.go 938 Bytes
一键复制 编辑 原始数据 按行查看 历史
HCY 提交于 2024-05-10 12:41 . c
package request
import (
"context"
"golang.org/x/time/rate"
"sync"
)
var globalTPSLimiter = NewTPSLimiter()
type TPSLimiter interface {
Limit(ctx context.Context, token string, tps float64, burst int)
}
func NewTPSLimiter() TPSLimiter {
return &multipleBucketLimiter{
buckets: make(map[string]*rate.Limiter),
}
}
// multipleBucketLimiter implements TPSLimiter with multiple bucket support.
type multipleBucketLimiter struct {
mu sync.Mutex
buckets map[string]*rate.Limiter
}
// Limit finds the given bucket, if bucket not exist or limit is changed,
// a new bucket will be generated.
func (m *multipleBucketLimiter) Limit(ctx context.Context, token string, tps float64, burst int) {
m.mu.Lock()
bucket, ok := m.buckets[token]
if !ok || float64(bucket.Limit()) != tps || bucket.Burst() != burst {
bucket = rate.NewLimiter(rate.Limit(tps), burst)
m.buckets[token] = bucket
}
m.mu.Unlock()
bucket.Wait(ctx)
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wuzheng0709/backend-gopkg.git
git@gitee.com:wuzheng0709/backend-gopkg.git
wuzheng0709
backend-gopkg
backend-gopkg
v1.4.12

搜索帮助