1 Star 0 Fork 0

simon/smallnest

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
req_rate_limiting.go 1.06 KB
一键复制 编辑 原始数据 按行查看 历史
simon 提交于 2021-09-04 14:58 +08:00 . 旧版
package serverplugin
import (
"context"
"time"
"github.com/juju/ratelimit"
"github.com/syndtr/goleveldb/leveldb/errors"
)
var ErrReqReachLimit = errors.New("request reached rate limit")
// ReqRateLimitingPlugin can limit requests per unit time
type ReqRateLimitingPlugin struct {
FillInterval time.Duration
Capacity int64
bucket *ratelimit.Bucket
block bool // blocks or return error if reach the limit
}
// NewReqRateLimitingPlugin creates a new RateLimitingPlugin
func NewReqRateLimitingPlugin(fillInterval time.Duration, capacity int64, block bool) *ReqRateLimitingPlugin {
tb := ratelimit.NewBucket(fillInterval, capacity)
return &ReqRateLimitingPlugin{
FillInterval: fillInterval,
Capacity: capacity,
bucket: tb,
block: block,
}
}
// PreReadRequest can limit request processing.
func (plugin *ReqRateLimitingPlugin) PreReadRequest(ctx context.Context) error {
if plugin.block {
plugin.bucket.Wait(1)
return nil
}
count := plugin.bucket.TakeAvailable(1)
if count == 1 {
return nil
}
return ErrReqReachLimit
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/simon_git_code/smallnest.git
git@gitee.com:simon_git_code/smallnest.git
simon_git_code
smallnest
smallnest
e483c3e07d35

搜索帮助