您现在的位置是:网站首页> 编程资料编程资料

Golang实现请求限流的几种办法(小结)_Golang_

2023-05-26 468人已围观

简介 Golang实现请求限流的几种办法(小结)_Golang_

在开发高并发系统时,有三把利器用来保护系统:缓存、降级和限流。那么何为限流呢?顾名思义,限流就是限制流量,就像你宽带包了1个G的流量,用完了就没了。

简单的并发控制

利用 channel 的缓冲设定,我们就可以来实现并发的限制。我们只要在执行并发的同时,往一个带有缓冲的 channel 里写入点东西(随便写啥,内容不重要)。让并发的 goroutine在执行完成后把这个 channel 里的东西给读走。这样整个并发的数量就讲控制在这个 channel的缓冲区大小上。

比如我们可以用一个 bool 类型的带缓冲 channel 作为并发限制的计数器。

 chLimit := make(chan bool, 1)

然后在并发执行的地方,每创建一个新的 goroutine,都往 chLimit 里塞个东西。

 for i, sleeptime := range input { chs[i] = make(chan string, 1) chLimit <- true go limitFunc(chLimit, chs[i], i, sleeptime, timeout) } 

这里通过 go 关键字并发执行的是新构造的函数。他在执行完后,会把 chLimit的缓冲区里给消费掉一个。

 limitFunc := func(chLimit chan bool, ch chan string, task_id, sleeptime, timeout int) { Run(task_id, sleeptime, timeout, ch) <-chLimit }

这样一来,当创建的 goroutine 数量到达 chLimit 的缓冲区上限后。主 goroutine 就挂起阻塞了,直到这些 goroutine 执行完毕,消费掉了 chLimit 缓冲区中的数据,程序才会继续创建新的 goroutine 。我们并发数量限制的目的也就达到了。

例子

 package main import ( "fmt" "time" ) func Run(task_id, sleeptime, timeout int, ch chan string) { ch_run := make(chan string) go run(task_id, sleeptime, ch_run) select { case re := <-ch_run: ch <- re case <-time.After(time.Duration(timeout) * time.Second): re := fmt.Sprintf("task id %d , timeout", task_id) ch <- re } } func run(task_id, sleeptime int, ch chan string) { time.Sleep(time.Duration(sleeptime) * time.Second) ch <- fmt.Sprintf("task id %d , sleep %d second", task_id, sleeptime) return } func main() { input := []int{3, 2, 1} timeout := 2 chLimit := make(chan bool, 1) chs := make([]chan string, len(input)) limitFunc := func(chLimit chan bool, ch chan string, task_id, sleeptime, timeout int) { Run(task_id, sleeptime, timeout, ch) <-chLimit } startTime := time.Now() fmt.Println("Multirun start") for i, sleeptime := range input { chs[i] = make(chan string, 1) chLimit <- true go limitFunc(chLimit, chs[i], i, sleeptime, timeout) } for _, ch := range chs { fmt.Println(<-ch) } endTime := time.Now() fmt.Printf("Multissh finished. Process time %s. Number of task is %d", endTime.Sub(startTime), len(input)) } 

运行结果:

Multirun start
     task id 0 , timeout
     task id 1 , timeout
     task id 2 , sleep 1 second
     Multissh finished. Process time 5s. Number of task is 3

如果修改并发限制为2:

 chLimit := make(chan bool, 2)

运行结果:

Multirun start
    task id 0 , timeout
    task id 1 , timeout
    task id 2 , sleep 1 second
    Multissh finished. Process time 3s. Number of task is 3

使用计数器实现请求限流

限流的要求是在指定的时间间隔内,server 最多只能服务指定数量的请求。实现的原理是我们启动一个计数器,每次服务请求会把计数器加一,同时到达指定的时间间隔后会把计数器清零;这个计数器的实现代码如下所示:

 type RequestLimitService struct { Interval time.Duration MaxCount int Lock sync.Mutex ReqCount int } func NewRequestLimitService(interval time.Duration, maxCnt int) *RequestLimitService { reqLimit := &RequestLimitService{ Interval: interval, MaxCount: maxCnt, } go func() { ticker := time.NewTicker(interval) for { <-ticker.C reqLimit.Lock.Lock() fmt.Println("Reset Count...") reqLimit.ReqCount = 0 reqLimit.Lock.Unlock() } }() return reqLimit } func (reqLimit *RequestLimitService) Increase() { reqLimit.Lock.Lock() defer reqLimit.Lock.Unlock() reqLimit.ReqCount += 1 } func (reqLimit *RequestLimitService) IsAvailable() bool { reqLimit.Lock.Lock() defer reqLimit.Lock.Unlock() return reqLimit.ReqCount < reqLimit.MaxCount } 

在服务请求的时候, 我们会对当前计数器和阈值进行比较,只有未超过阈值时才进行服务:

 var RequestLimit = NewRequestLimitService(10 * time.Second, 5) func helloHandler(w http.ResponseWriter, r *http.Request) { if RequestLimit.IsAvailable() { RequestLimit.Increase() fmt.Println(RequestLimit.ReqCount) io.WriteString(w, "Hello world!\n") } else { fmt.Println("Reach request limiting!") io.WriteString(w, "Reach request limit!\n") } } func main() { fmt.Println("Server Started!") http.HandleFunc("/", helloHandler) http.ListenAndServe(":8000", nil) } 

完整代码 url

使用golang官方包实现httpserver频率限制

使用golang来编写httpserver时,可以使用官方已经有实现好的包:

 import( "fmt" "net" "golang.org/x/net/netutil" ) func main() { l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { fmt.Fatalf("Listen: %v", err) } defer l.Close() l = LimitListener(l, max) http.Serve(l, http.HandlerFunc()) //bla bla bla................. } 

源码[url] ( https://github.com/golang/net/blob/master/netutil/listen.go ),基本思路就是为连接数计数,通过make chan来建立一个最大连接数的channel, 每次accept就+1,close时候就-1. 当到达最大连接数时,就等待空闲连接出来之后再accept。

 // Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package netutil provides network utility functions, complementing the more // common ones in the net package. package netutil // import "golang.org/x/net/netutil" import ( "net" "sync" ) // LimitListener returns a Listener that accepts at most n simultaneous // connections from the provided Listener. func LimitListener(l net.Listener, n int) net.Listener { return &limitListener{ Listener: l, sem: make(chan struct{}, n), done: make(chan struct{}), } } type limitListener struct { net.Listener sem chan struct{} closeOnce sync.Once // ensures the done chan is only closed once done chan struct{} // no values sent; closed when Close is called } // acquire acquires the limiting semaphore. Returns true if successfully // accquired, false if the listener is closed and the semaphore is not // acquired. func (l *limitListener) acquire() bool { select { case <-l.done: return false case l.sem <- struct{}{}: return true } } func (l *limitListener) release() { <-l.sem } func (l *limitListener) Accept() (net.Conn, error) { //如果sem满了,就会阻塞在这 acquired := l.acquire() // If the semaphore isn't acquired because the listener was closed, expect // that this call to accept won't block, but immediately return an error. c, err := l.Listener.Accept() if err != nil { if acquired { l.release() } return nil, err } return &limitListenerConn{Conn: c, release: l.release}, nil } func (l *limitListener) Close() error { err := l.Listener.Close() l.closeOnce.Do(func() { close(l.done) }) return err } type limitListenerConn struct { net.Conn releaseOnce sync.Once release func() } func (l *limitListenerConn) Close() error { err := l.Conn.Close() //close时释放占用的sem l.releaseOnce.Do(l.release) return err } 

使用Token Bucket(令牌桶算法)实现请求限流

在开发高并发系统时有三把利器用来保护系统:缓存、降级和限流!为了保证在业务高峰期,线上系统也能保证一定的弹性和稳定性,最有效的方案就是进行服务降级了,而限流就是降级系统最常采用的方案之一。

这里为大家推荐一个开源库 https://github.com/didip/tollbooth ,但是,如果您想要一些简单的、轻量级的或者只是想要学习的东西,实现自己的中间件来处理速率限制并不困难。今天我们就来聊聊如何实现自己的一个限流中间件

首先我们需要安装一个提供了 Token bucket (令牌桶算法)的依赖包,上面提到的toolbooth 的实现也是基于它实现的:

 $ go get golang.org/x/time/rate

Demo代码的实现

 package main import ( "net/http" "golang.org/x/time/rate" ) var limiter = rate.NewLimiter(2, 5) func limit(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if limiter.Allow() == false { http.Error(w, http.StatusText(429), http.StatusTooManyRequests) return } next.ServeHTTP(w, r) }) } func main() { mux := http.NewServeMux() mux.HandleFunc("/", okHandler) // Wrap the servemux with the limit middleware. http.ListenAndServe(":4000", limit(mux)) } func okHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("OK")) } 

算法描述:用户配置的平均发送速率为r,则每隔1/r秒一个令牌被加入到桶中(每秒会有r个令牌放入桶中),桶中最多可以存放b个令牌。如果令牌到达时令牌桶已经满了,那么这个令牌会被丢弃;

实现

 // Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package rate provides a rate limiter. package rate import ( "fmt" "math" "sync" "time" "golang.org/x/net/context" ) // Limit defines the maximum frequency of some events. // Limit is represented as number of events per second. // A zero Limit allows no events. type Limit float64 // Inf is the infinite rate limit; it allows all events (even if burst is zero). const Inf = Limit(math.MaxFloat64) // Every converts a minimum time interval between events to a Limit. func Every(interval time.Duration) Limit { if interval <= 0 { return Inf } return 1 / Limit(interval.Seconds()) } // A Limiter controls how frequently events are allowed to happen. // It implements a "token bucket" of size b, initially full and refilled // at rate r tokens per second. // Informally, in any large enough time interval, the Limiter limits the // rate to r tokens per second, with a maximum burst size of b events. // As a special case, if r == Inf (the infinite rate), b is ignored. // See https://en.wikipedia.org/wiki/Token_bucket for more about token buckets. // // The zero value is a valid Limiter, but it will reject all events. // Use NewLimiter to create non-zero Limiters. // // Limiter has three main methods, Allow, Reserve, and Wait. // M
                
                

-六神源码网