dongxiaoxing3058 2019-02-27 07:25
浏览 234

限速功能40 /秒,带有“”

I'm trying to use "" 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


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 为啥快手广告联盟的广告这么难出来
  • ¥15 k8s集群重启后,kubelet一直报systemctl restart kubelet.service "Failed to delete cgroup paths"
  • ¥15 微信小程序构建工具类发布到npm,install后报错
  • ¥15 amesim液压仿真问题
  • ¥15 MATLAB优化设计
  • ¥15 ANN预测模型 200大米
  • ¥20 优秀学生的问题 oj java
  • ¥15 scratch-gui 如何集成进 react native
  • ¥15 把全局悬浮窗改为局内悬浮窗
  • ¥15 Excel vba编程调用word如何读取换行符