2 Star 1 Fork 1

mosache/YFrame

Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
Clone or Download
token_bucket.go 1.14 KB
Copy Edit Raw Blame History
ヤ沒脩袮兲︶ authored 2023-09-12 18:29 . temp
package ratelimit
import (
"context"
"github.com/zeromicro/go-zero/core/syncx"
"google.golang.org/grpc"
"time"
)
// 令牌桶
type TokenBucketLimiter struct {
tokens chan struct{}
ch chan struct{}
}
func NewTokenBucketLimiter(capacity int, interval time.Duration) *TokenBucketLimiter {
tokens := make(chan struct{}, capacity)
closeCh := make(chan struct{})
ticker := time.NewTicker(interval)
go func() {
defer ticker.Stop()
for {
select {
case <-ticker.C:
select {
case tokens <- struct{}{}:
default:
}
case <-closeCh:
break
default:
}
}
}()
return &TokenBucketLimiter{
tokens: tokens,
ch: closeCh,
}
}
func (t *TokenBucketLimiter) Build() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
select {
case <-t.ch:
/// 关闭了limiter,直接通过
resp, err = handler(ctx, req)
case <-t.tokens:
resp, err = handler(ctx, req)
case <-ctx.Done():
err = ctx.Err()
}
return
}
}
func (t *TokenBucketLimiter) Close() {
syncx.Once(func() {
close(t.ch)
})
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/mosache/YFrame.git
git@gitee.com:mosache/YFrame.git
mosache
YFrame
YFrame
v0.1.56

Search