github.com/songzhibin97/gkit@v1.2.13/restrictor/ratelimite/example_test.go (about)

     1  package ratelimite
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	"github.com/juju/ratelimit"
     8  )
     9  
    10  func ExampleNewRateLimit() {
    11  	// ratelimit github.com/juju/ratelimit
    12  	bucket := ratelimit.NewBucket(time.Second/2, 4)
    13  
    14  	af, wf := NewRateLimit(bucket)
    15  	// af.Allow()bool: 默认取1个token
    16  	// af.Allow() == af.AllowN(time.Now(), 1)
    17  	af.Allow()
    18  
    19  	// af.AllowN(ctx,n)bool: 可以取N个token
    20  	af.AllowN(time.Now(), 5)
    21  
    22  	// wf.Wait(ctx) err: 等待ctx超时,默认取1个token
    23  	// wf.Wait(ctx) == wf.WaitN(ctx, 1)
    24  	_ = wf.Wait(context.TODO())
    25  
    26  	// wf.WaitN(ctx, n) err: 等待ctx超时,可以取N个token
    27  	_ = wf.WaitN(context.TODO(), 5)
    28  }