dongxiaoxing3058 2019-02-27 07:25
浏览 235
已采纳

限速功能40 /秒,带有“ golang.org/x/time/rate”

I'm trying to use "golang.org/x/time/rate" to build a function which blocks until a token is free. Is this the correct way to use the library to rate limit blocks of code to 40 requests per second, with a bucket size of 2.

type Client struct {
    limiter        *rate.Limiter
    ctx context.Context
}

func NewClient() *Client {
    c :=Client{}
    c.limiter = rate.NewLimiter(40, 2)
    c.ctx = context.Background()
    return &c
}

func (client *Client) RateLimitFunc() {

    err := client.limiter.Wait(client.ctx)
    if err != nil {
        fmt.Printf("rate limit error: %v", err)
    }
}

To rate limit a block of code I call

RateLimitFunc()

I don't want to use a ticker as I want the rate limiter to take into account the length of time the calling code runs for.

  • 写回答

1条回答 默认 最新

  • doulu1945 2019-02-27 07:58
    关注

    Reading the docs here; link

    You can see that the first param to NewLimiter is of type rate.Limit.

    If you want 40 requests / second then that translates into a rate of 1 requests every 25ms.

    You can create that by doing:

    limiter := rate.NewLimiter(rate.Every(25 * time.Millisecond), 2)
    

    Side note:

    • In generate a context ctx should not be stored on a struct and should be per-request. It would appear that Client will be reused, thus you could pass a context to the RateLimitFunc() or where ever appropriate instead of storing a single context on the client struct.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 cplex运行后参数报错是为什么
  • ¥15 之前不小心删了pycharm的文件,后面重新安装之后软件打不开了
  • ¥15 vue3获取动态宽度,刷新后动态宽度值为0
  • ¥15 升腾威讯云桌面V2.0.0摄像头问题
  • ¥15 关于Python的会计设计
  • ¥15 聚类分析 设计k-均值算法分类器,对一组二维模式向量进行分类。
  • ¥15 stm32c8t6工程,使用hal库
  • ¥15 找能接spark如图片的,可议价
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 博通raid 的写入速度很高也很低