我有一个 URL 列表,我需要使用 goroutine 来同时触发 HTTP 请求。无论如何检查和限制每秒发送多少 HTTP 请求?
最佳答案
Go 中的一个非常简单的版本是对 Leaky Bucket 的改编。算法,使用 channel 和协程。在发出请求之前从 rate
channel 接收 token 将检查速率并在速率限制器为空时阻止。
// create a buffered channel.
// The capacity of the channel is maximum burst that can be made.
rate := make(chan struct{}, 10)
go func() {
ticker := time.NewTicker(100 * time.Millisecond)
for range ticker.C {
rate <- struct{}{}
}
}()
由于一系列耗时超过平均速率的请求最终会并发,因此您可能也需要限制并发。您可以添加第二个 channel 作为信号量,在发出请求之前向信号量添加 token ,并在请求完成后将其删除。
// limit concurrency to 5
semaphore := make(chan struct{}, 5)
// in request function
semaphore <- struct{}{}
defer func() {
<-semaphore
}()
这里有一个更完整的例子:
关于http - 是否可以限制每秒运行多少个 goroutines?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43789362/