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

限速功能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 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来