本文整理匯總了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)
}))
}