分类目录归档:go

Golang Rate Limit流控

通常一个稳健的系统需要有一定的熔断或流控机制,用来防止突发或异常请求造成系统过高占用, 致使系统无法正常运作.
Go中无需使用第三方库,就可以很容易就可以做到流控.

QPS控制,10 QPS

通过Ticker触发消息,达到流控目的

import "time"

rate := time.Second / 10
throttle := time.Tick(rate)
for req := range requests {
  <-throttle  // rate limit our Service.Method RPCs
  go client.Call("Service.Method", req, ...)
}
import "time"

rate := time.Second / 10
burstLimit := 100
tick := time.NewTicker(rate)
defer tick.Stop()
throttle := make(chan time.Time, burstLimit)
go func() {
  for t := range tick.C {
    select {
      case throttle <- t:
      default:
    }
  }  // does not exit after tick.Stop()
}()
for req := range requests {
  <-throttle  // rate limit our Service.Method RPCs
  go client.Call("Service.Method", req, ...)
}