Метод 1: ограничение скорости во время сна
package main
import (
"fmt"
"time"
)
func main() {
rate := time.Second * 2 // Allow 2 requests per second
for i := 1; i <= 10; i++ {
makeRequest(i)
time.Sleep(rate)
}
}
func makeRequest(requestNumber int) {
fmt.Printf("Processing request %d\n", requestNumber)
// Perform your request logic here
}
Метод 2. Алгоритм сегмента токенов
package main
import (
"fmt"
"time"
)
func main() {
rate := time.Second * 2 // Allow 2 requests per second
bucket := make(chan struct{}, 10) // Bucket with a capacity of 10 tokens
go func() {
for {
bucket <- struct{}{}
// Add token to the bucket every rate duration
time.Sleep(rate)
}
}()
for i := 1; i <= 10; i++ {
<-bucket // Wait for a token from the bucket
makeRequest(i)
}
}
func makeRequest(requestNumber int) {
fmt.Printf("Processing request %d\n", requestNumber)
// Perform your request logic here
}
Метод 3. Алгоритм дырявого ведра
package main
import (
"fmt"
"sync"
"time"
)
func main() {
rate := time.Second * 2 // Allow 2 requests per second
var wg sync.WaitGroup
for i := 1; i <= 10; i++ {
wg.Add(1)
go func(requestNumber int) {
defer wg.Done()
makeRequest(requestNumber)
}(i)
time.Sleep(rate)
}
wg.Wait()
}
func makeRequest(requestNumber int) {
fmt.Printf("Processing request %d\n", requestNumber)
// Perform your request logic here
}
Метод 4. Алгоритм скользящего окна
package main
import (
"fmt"
"sync"
"time"
)
func main() {
rate := time.Second * 2 // Allow 2 requests per second
windowSize := 5 // Number of requests allowed within the window
var mu sync.Mutex
var count int
for i := 1; i <= 10; i++ {
mu.Lock()
count++
if count > windowSize {
mu.Unlock()
time.Sleep(rate)
mu.Lock()
count = 1
}
mu.Unlock()
go makeRequest(i)
}
}
func makeRequest(requestNumber int) {
fmt.Printf("Processing request %d\n", requestNumber)
// Perform your request logic here
}
Это всего лишь несколько методов реализации ограничения скорости в Go. Каждый метод имеет свои преимущества и варианты использования, поэтому выберите тот, который лучше всего соответствует вашим требованиям. Помните, что ограничение скорости помогает предотвратить перегрузку вашим кодом внешних ресурсов, обеспечивая плавный и контролируемый поток запросов.
Так что следите за тем, чтобы ваш код был гидратированным и наслаждался ограничением скорости в Go!