本文整理汇总了Golang中github.com/juju/ratelimit.Bucket.TakeAvailable方法的典型用法代码示例。如果您正苦于以下问题:Golang Bucket.TakeAvailable方法的具体用法?Golang Bucket.TakeAvailable怎么用?Golang Bucket.TakeAvailable使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/juju/ratelimit.Bucket
的用法示例。
在下文中一共展示了Bucket.TakeAvailable方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: limit
func limit(b *ratelimit.Bucket, wait bool, errId string) func() error {
return func() error {
if wait {
time.Sleep(b.Take(1))
} else if b.TakeAvailable(1) == 0 {
return errors.New(errId, "too many request", 429)
}
return nil
}
}
示例2: NewTokenBucketLimiter
// NewTokenBucketLimiter returns an endpoint.Middleware that acts as a rate
// limiter based on a token-bucket algorithm. Requests that would exceed the
// maximum request rate are simply rejected with an error.
func NewTokenBucketLimiter(tb *ratelimit.Bucket) endpoint.Middleware {
return func(next endpoint.Endpoint) endpoint.Endpoint {
return func() error {
if tb.TakeAvailable(1) == 0 {
return ErrLimited
}
return next()
}
}
}
示例3: NewTokenBucketLimiter
func NewTokenBucketLimiter(tb *ratelimit.Bucket) endpoint.Middleware {
return func(next endpoint.Endpoint) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
if tb.TakeAvailable(1) == 0 { // HL
return nil, ErrLimited // HL
} // HL
return next(ctx, request) // HL
}
}
}
示例4: getTestServerThrottled
func getTestServerThrottled(body string) *httptest.Server {
var rateLimiter *ratelimit.Bucket
// Rate limit: 2 req/s, capacity 2
rateLimiter = ratelimit.NewBucket(500*time.Millisecond, 2)
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
code := 200
if tokens := rateLimiter.TakeAvailable(1); tokens == 0 {
code = 503
}
w.WriteHeader(code)
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, body)
}))
}