1. 程式人生 > 實用技巧 >Golang實現請求限流的幾種辦法

Golang實現請求限流的幾種辦法

目錄

簡單的併發控制

使用計數器實現請求限流

使用golang官方包實現httpserver頻率限制

使用Token Bucket(令牌桶演算法)實現請求限流


簡單的併發控制

利用 channel 的緩衝設定,我們就可以來實現併發的限制。我們只要在執行併發的同時,往一個帶有緩衝的channel裡寫入點東西(隨便寫啥,內容不重要)。讓併發的goroutine在執行完成後把這個channel裡的東西給讀走。這樣整個併發的數量就講控制在這個channel的緩衝區大小上。

比如我們可以用一個bool型別的帶緩衝channel作為併發限制的計數器。

chLimit := make(chan bool, 1)

然後在併發執行的地方,每建立一個新的 goroutine,都往chLimit裡塞個東西。

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

這裡通過go關鍵字併發執行的是新構造的函式。他在執行完後,會把chLimit的緩衝區裡給消費掉一個。

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

這樣一來,當建立的goroutine數量到達chLimit的緩衝區上限後。主goroutine就掛起阻塞了,直到這些goroutine執行完畢,消費掉了chLimit緩衝區中的資料,程式才會繼續建立新的goroutine。我們併發數量限制的目的也就達到了。

以下是完整程式碼:

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func Run(task_id, sleeptime, timeout int, ch chan string) {
  7. ch_run := make(chan string)
  8. go run(task_id, sleeptime, ch_run)
  9. select {
  10. case re := <-ch_run:
  11. ch <- re
  12. case <-time.After(time.Duration(timeout) * time.Second):
  13. re := fmt.Sprintf("task id %d , timeout", task_id)
  14. ch <- re
  15. }
  16. }
  17. func run(task_id, sleeptime int, ch chan string) {
  18. time.Sleep(time.Duration(sleeptime) * time.Second)
  19. ch <- fmt.Sprintf("task id %d , sleep %d second", task_id, sleeptime)
  20. return
  21. }
  22. func main() {
  23. input := []int{3, 2, 1}
  24. timeout := 2
  25. chLimit := make(chan bool, 1)
  26. chs := make([]chan string, len(input))
  27. limitFunc := func(chLimit chan bool, ch chan string, task_id, sleeptime, timeout int) {
  28. Run(task_id, sleeptime, timeout, ch)
  29. <-chLimit
  30. }
  31. startTime := time.Now()
  32. fmt.Println("Multirun start")
  33. for i, sleeptime := range input {
  34. chs[i] = make(chan string, 1)
  35. chLimit <- true
  36. go limitFunc(chLimit, chs[i], i, sleeptime, timeout)
  37. }
  38. for _, ch := range chs {
  39. fmt.Println(<-ch)
  40. }
  41. endTime := time.Now()
  42. fmt.Printf("Multissh finished. Process time %s. Number of task is %d", endTime.Sub(startTime), len(input))
  43. }

執行結果:

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

如果修改併發限制為2:

chLimit := make(chan bool, 2)

執行結果:

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

使用計數器實現請求限流

限流的要求是在指定的時間間隔內,server 最多隻能服務指定數量的請求。實現的原理是我們啟動一個計數器,每次服務請求會把計數器加一,同時到達指定的時間間隔後會把計數器清零;這個計數器的實現程式碼如下所示:

  1. type RequestLimitService struct {
  2. Interval time.Duration
  3. MaxCount int
  4. Lock sync.Mutex
  5. ReqCount int
  6. }
  7. func NewRequestLimitService(interval time.Duration, maxCnt int) *RequestLimitService {
  8. reqLimit := &RequestLimitService{
  9. Interval: interval,
  10. MaxCount: maxCnt,
  11. }
  12. go func() {
  13. ticker := time.NewTicker(interval)
  14. for {
  15. <-ticker.C
  16. reqLimit.Lock.Lock()
  17. fmt.Println("Reset Count...")
  18. reqLimit.ReqCount = 0
  19. reqLimit.Lock.Unlock()
  20. }
  21. }()
  22. return reqLimit
  23. }
  24. func (reqLimit *RequestLimitService) Increase() {
  25. reqLimit.Lock.Lock()
  26. defer reqLimit.Lock.Unlock()
  27. reqLimit.ReqCount += 1
  28. }
  29. func (reqLimit *RequestLimitService) IsAvailable() bool {
  30. reqLimit.Lock.Lock()
  31. defer reqLimit.Lock.Unlock()
  32. return reqLimit.ReqCount < reqLimit.MaxCount
  33. }

在服務請求的時候, 我們會對當前計數器和閾值進行比較,只有未超過閾值時才進行服務:

  1. var RequestLimit = NewRequestLimitService(10 * time.Second, 5)
  2. func helloHandler(w http.ResponseWriter, r *http.Request) {
  3. if RequestLimit.IsAvailable() {
  4. RequestLimit.Increase()
  5. fmt.Println(RequestLimit.ReqCount)
  6. io.WriteString(w, "Hello world!\n")
  7. } else {
  8. fmt.Println("Reach request limiting!")
  9. io.WriteString(w, "Reach request limit!\n")
  10. }
  11. }
  12. func main() {
  13. fmt.Println("Server Started!")
  14. http.HandleFunc("/", helloHandler)
  15. http.ListenAndServe(":8000", nil)
  16. }

完整程式碼url:https://github.com/hiberabyss/JustDoIt/blob/master/RequestLimit/request_limit.go

使用golang官方包實現httpserver頻率限制

使用golang來編寫httpserver時,可以使用官方已經有實現好的包:

  1. import(
  2. "fmt"
  3. "net"
  4. "golang.org/x/net/netutil"
  5. )
  6. func main() {
  7. l, err := net.Listen("tcp", "127.0.0.1:0")
  8. if err != nil {
  9. fmt.Fatalf("Listen: %v", err)
  10. }
  11. defer l.Close()
  12. l = LimitListener(l, max)
  13. http.Serve(l, http.HandlerFunc())
  14. //bla bla bla.................
  15. }

原始碼如下(url :https://github.com/golang/net/blob/master/netutil/listen.go),基本思路就是為連線數計數,通過make chan來建立一個最大連線數的channel, 每次accept就+1,close時候就-1. 當到達最大連線數時,就等待空閒連接出來之後再accept。

  1. // Copyright 2013 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package netutil provides network utility functions, complementing the more
  5. // common ones in the net package.
  6. package netutil // import "golang.org/x/net/netutil"
  7. import (
  8. "net"
  9. "sync"
  10. )
  11. // LimitListener returns a Listener that accepts at most n simultaneous
  12. // connections from the provided Listener.
  13. func LimitListener(l net.Listener, n int) net.Listener {
  14. return &limitListener{
  15. Listener: l,
  16. sem: make(chan struct{}, n),
  17. done: make(chan struct{}),
  18. }
  19. }
  20. type limitListener struct {
  21. net.Listener
  22. sem chan struct{}
  23. closeOnce sync.Once // ensures the done chan is only closed once
  24. done chan struct{} // no values sent; closed when Close is called
  25. }
  26. // acquire acquires the limiting semaphore. Returns true if successfully
  27. // accquired, false if the listener is closed and the semaphore is not
  28. // acquired.
  29. func (l *limitListener) acquire() bool {
  30. select {
  31. case <-l.done:
  32. return false
  33. case l.sem <- struct{}{}:
  34. return true
  35. }
  36. }
  37. func (l *limitListener) release() { <-l.sem }
  38. func (l *limitListener) Accept() (net.Conn, error) {
  39. //如果sem滿了,就會阻塞在這
  40. acquired := l.acquire()
  41. // If the semaphore isn't acquired because the listener was closed, expect
  42. // that this call to accept won't block, but immediately return an error.
  43. c, err := l.Listener.Accept()
  44. if err != nil {
  45. if acquired {
  46. l.release()
  47. }
  48. return nil, err
  49. }
  50. return &limitListenerConn{Conn: c, release: l.release}, nil
  51. }
  52. func (l *limitListener) Close() error {
  53. err := l.Listener.Close()
  54. l.closeOnce.Do(func() { close(l.done) })
  55. return err
  56. }
  57. type limitListenerConn struct {
  58. net.Conn
  59. releaseOnce sync.Once
  60. release func()
  61. }
  62. func (l *limitListenerConn) Close() error {
  63. err := l.Conn.Close()
  64. //close時釋放佔用的sem
  65. l.releaseOnce.Do(l.release)
  66. return err
  67. }

使用Token Bucket(令牌桶演算法)實現請求限流

在開發高併發系統時有三把利器用來保護系統:快取、降級和限流!為了保證在業務高峰期,線上系統也能保證一定的彈性和穩定性,最有效的方案就是進行服務降級了,而限流就是降級系統最常採用的方案之一。

這裡為大家推薦一個開源庫https://github.com/didip/tollbooth,但是,如果您想要一些簡單的、輕量級的或者只是想要學習的東西,實現自己的中介軟體來處理速率限制並不困難。今天我們就來聊聊如何實現自己的一個限流中介軟體

首先我們需要安裝一個提供了Token bucket(令牌桶演算法)的依賴包,上面提到的toolbooth 的實現也是基於它實現的:

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

先看Demo程式碼的實現:

  1. package main
  2. import (
  3. "net/http"
  4. "golang.org/x/time/rate"
  5. )
  6. var limiter = rate.NewLimiter(2, 5)
  7. func limit(next http.Handler) http.Handler {
  8. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  9. if limiter.Allow() == false {
  10. http.Error(w, http.StatusText(429), http.StatusTooManyRequests)
  11. return
  12. }
  13. next.ServeHTTP(w, r)
  14. })
  15. }
  16. func main() {
  17. mux := http.NewServeMux()
  18. mux.HandleFunc("/", okHandler)
  19. // Wrap the servemux with the limit middleware.
  20. http.ListenAndServe(":4000", limit(mux))
  21. }
  22. func okHandler(w http.ResponseWriter, r *http.Request) {
  23. w.Write([]byte("OK"))
  24. }

然後看看rate.NewLimiter的原始碼:

演算法描述:使用者配置的平均傳送速率為r,則每隔1/r秒一個令牌被加入到桶中(每秒會有r個令牌放入桶中),桶中最多可以存放b個令牌。如果令牌到達時令牌桶已經滿了,那麼這個令牌會被丟棄;

  1. // Copyright 2015 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package rate provides a rate limiter.
  5. package rate
  6. import (
  7. "fmt"
  8. "math"
  9. "sync"
  10. "time"
  11. "golang.org/x/net/context"
  12. )
  13. // Limit defines the maximum frequency of some events.
  14. // Limit is represented as number of events per second.
  15. // A zero Limit allows no events.
  16. type Limit float64
  17. // Inf is the infinite rate limit; it allows all events (even if burst is zero).
  18. const Inf = Limit(math.MaxFloat64)
  19. // Every converts a minimum time interval between events to a Limit.
  20. func Every(interval time.Duration) Limit {
  21. if interval <= 0 {
  22. return Inf
  23. }
  24. return 1 / Limit(interval.Seconds())
  25. }
  26. // A Limiter controls how frequently events are allowed to happen.
  27. // It implements a "token bucket" of size b, initially full and refilled
  28. // at rate r tokens per second.
  29. // Informally, in any large enough time interval, the Limiter limits the
  30. // rate to r tokens per second, with a maximum burst size of b events.
  31. // As a special case, if r == Inf (the infinite rate), b is ignored.
  32. // See https://en.wikipedia.org/wiki/Token_bucket for more about token buckets.
  33. //
  34. // The zero value is a valid Limiter, but it will reject all events.
  35. // Use NewLimiter to create non-zero Limiters.
  36. //
  37. // Limiter has three main methods, Allow, Reserve, and Wait.
  38. // Most callers should use Wait.
  39. //
  40. // Each of the three methods consumes a single token.
  41. // They differ in their behavior when no token is available.
  42. // If no token is available, Allow returns false.
  43. // If no token is available, Reserve returns a reservation for a future token
  44. // and the amount of time the caller must wait before using it.
  45. // If no token is available, Wait blocks until one can be obtained
  46. // or its associated context.Context is canceled.
  47. //
  48. // The methods AllowN, ReserveN, and WaitN consume n tokens.
  49. type Limiter struct {
  50. //maximum token, token num per second
  51. limit Limit
  52. //burst field, max token num
  53. burst int
  54. mu sync.Mutex
  55. //tokens num, change
  56. tokens float64
  57. // last is the last time the limiter's tokens field was updated
  58. last time.Time
  59. // lastEvent is the latest time of a rate-limited event (past or future)
  60. lastEvent time.Time
  61. }
  62. // Limit returns the maximum overall event rate.
  63. func (lim *Limiter) Limit() Limit {
  64. lim.mu.Lock()
  65. defer lim.mu.Unlock()
  66. return lim.limit
  67. }
  68. // Burst returns the maximum burst size. Burst is the maximum number of tokens
  69. // that can be consumed in a single call to Allow, Reserve, or Wait, so higher
  70. // Burst values allow more events to happen at once.
  71. // A zero Burst allows no events, unless limit == Inf.
  72. func (lim *Limiter) Burst() int {
  73. return lim.burst
  74. }
  75. // NewLimiter returns a new Limiter that allows events up to rate r and permits
  76. // bursts of at most b tokens.
  77. func NewLimiter(r Limit, b int) *Limiter {
  78. return &Limiter{
  79. limit: r,
  80. burst: b,
  81. }
  82. }
  83. // Allow is shorthand for AllowN(time.Now(), 1).
  84. func (lim *Limiter) Allow() bool {
  85. return lim.AllowN(time.Now(), 1)
  86. }
  87. // AllowN reports whether n events may happen at time now.
  88. // Use this method if you intend to drop / skip events that exceed the rate limit.
  89. // Otherwise use Reserve or Wait.
  90. func (lim *Limiter) AllowN(now time.Time, n int) bool {
  91. return lim.reserveN(now, n, 0).ok
  92. }
  93. // A Reservation holds information about events that are permitted by a Limiter to happen after a delay.
  94. // A Reservation may be canceled, which may enable the Limiter to permit additional events.
  95. type Reservation struct {
  96. ok bool
  97. lim *Limiter
  98. tokens int
  99. //This is the time to action
  100. timeToAct time.Time
  101. // This is the Limit at reservation time, it can change later.
  102. limit Limit
  103. }
  104. // OK returns whether the limiter can provide the requested number of tokens
  105. // within the maximum wait time. If OK is false, Delay returns InfDuration, and
  106. // Cancel does nothing.
  107. func (r *Reservation) OK() bool {
  108. return r.ok
  109. }
  110. // Delay is shorthand for DelayFrom(time.Now()).
  111. func (r *Reservation) Delay() time.Duration {
  112. return r.DelayFrom(time.Now())
  113. }
  114. // InfDuration is the duration returned by Delay when a Reservation is not OK.
  115. const InfDuration = time.Duration(1<<63 - 1)
  116. // DelayFrom returns the duration for which the reservation holder must wait
  117. // before taking the reserved action. Zero duration means act immediately.
  118. // InfDuration means the limiter cannot grant the tokens requested in this
  119. // Reservation within the maximum wait time.
  120. func (r *Reservation) DelayFrom(now time.Time) time.Duration {
  121. if !r.ok {
  122. return InfDuration
  123. }
  124. delay := r.timeToAct.Sub(now)
  125. if delay < 0 {
  126. return 0
  127. }
  128. return delay
  129. }
  130. // Cancel is shorthand for CancelAt(time.Now()).
  131. func (r *Reservation) Cancel() {
  132. r.CancelAt(time.Now())
  133. return
  134. }
  135. // CancelAt indicates that the reservation holder will not perform the reserved action
  136. // and reverses the effects of this Reservation on the rate limit as much as possible,
  137. // considering that other reservations may have already been made.
  138. func (r *Reservation) CancelAt(now time.Time) {
  139. if !r.ok {
  140. return
  141. }
  142. r.lim.mu.Lock()
  143. defer r.lim.mu.Unlock()
  144. if r.lim.limit == Inf || r.tokens == 0 || r.timeToAct.Before(now) {
  145. return
  146. }
  147. // calculate tokens to restore
  148. // The duration between lim.lastEvent and r.timeToAct tells us how many tokens were reserved
  149. // after r was obtained. These tokens should not be restored.
  150. restoreTokens := float64(r.tokens) - r.limit.tokensFromDuration(r.lim.lastEvent.Sub(r.timeToAct))
  151. if restoreTokens <= 0 {
  152. return
  153. }
  154. // advance time to now
  155. now, _, tokens := r.lim.advance(now)
  156. // calculate new number of tokens
  157. tokens += restoreTokens
  158. if burst := float64(r.lim.burst); tokens > burst {
  159. tokens = burst
  160. }
  161. // update state
  162. r.lim.last = now
  163. r.lim.tokens = tokens
  164. if r.timeToAct == r.lim.lastEvent {
  165. prevEvent := r.timeToAct.Add(r.limit.durationFromTokens(float64(-r.tokens)))
  166. if !prevEvent.Before(now) {
  167. r.lim.lastEvent = prevEvent
  168. }
  169. }
  170. return
  171. }
  172. // Reserve is shorthand for ReserveN(time.Now(), 1).
  173. func (lim *Limiter) Reserve() *Reservation {
  174. return lim.ReserveN(time.Now(), 1)
  175. }
  176. // ReserveN returns a Reservation that indicates how long the caller must wait before n events happen.
  177. // The Limiter takes this Reservation into account when allowing future events.
  178. // ReserveN returns false if n exceeds the Limiter's burst size.
  179. // Usage example:
  180. // r, ok := lim.ReserveN(time.Now(), 1)
  181. // if !ok {
  182. // // Not allowed to act! Did you remember to set lim.burst to be > 0 ?
  183. // }
  184. // time.Sleep(r.Delay())
  185. // Act()
  186. // Use this method if you wish to wait and slow down in accordance with the rate limit without dropping events.
  187. // If you need to respect a deadline or cancel the delay, use Wait instead.
  188. // To drop or skip events exceeding rate limit, use Allow instead.
  189. func (lim *Limiter) ReserveN(now time.Time, n int) *Reservation {
  190. r := lim.reserveN(now, n, InfDuration)
  191. return &r
  192. }
  193. // Wait is shorthand for WaitN(ctx, 1).
  194. func (lim *Limiter) Wait(ctx context.Context) (err error) {
  195. return lim.WaitN(ctx, 1)
  196. }
  197. // WaitN blocks until lim permits n events to happen.
  198. // It returns an error if n exceeds the Limiter's burst size, the Context is
  199. // canceled, or the expected wait time exceeds the Context's Deadline.
  200. func (lim *Limiter) WaitN(ctx context.Context, n int) (err error) {
  201. if n > lim.burst {
  202. return fmt.Errorf("rate: Wait(n=%d) exceeds limiter's burst %d", n, lim.burst)
  203. }
  204. // Check if ctx is already cancelled
  205. select {
  206. case <-ctx.Done():
  207. return ctx.Err()
  208. default:
  209. }
  210. // Determine wait limit
  211. now := time.Now()
  212. waitLimit := InfDuration
  213. if deadline, ok := ctx.Deadline(); ok {
  214. waitLimit = deadline.Sub(now)
  215. }
  216. // Reserve
  217. r := lim.reserveN(now, n, waitLimit)
  218. if !r.ok {
  219. return fmt.Errorf("rate: Wait(n=%d) would exceed context deadline", n)
  220. }
  221. // Wait
  222. t := time.NewTimer(r.DelayFrom(now))
  223. defer t.Stop()
  224. select {
  225. case <-t.C:
  226. // We can proceed.
  227. return nil
  228. case <-ctx.Done():
  229. // Context was canceled before we could proceed. Cancel the
  230. // reservation, which may permit other events to proceed sooner.
  231. r.Cancel()
  232. return ctx.Err()
  233. }
  234. }
  235. // SetLimit is shorthand for SetLimitAt(time.Now(), newLimit).
  236. func (lim *Limiter) SetLimit(newLimit Limit) {
  237. lim.SetLimitAt(time.Now(), newLimit)
  238. }
  239. // SetLimitAt sets a new Limit for the limiter. The new Limit, and Burst, may be violated
  240. // or underutilized by those which reserved (using Reserve or Wait) but did not yet act
  241. // before SetLimitAt was called.
  242. func (lim *Limiter) SetLimitAt(now time.Time, newLimit Limit) {
  243. lim.mu.Lock()
  244. defer lim.mu.Unlock()
  245. now, _, tokens := lim.advance(now)
  246. lim.last = now
  247. lim.tokens = tokens
  248. lim.limit = newLimit
  249. }
  250. // reserveN is a helper method for AllowN, ReserveN, and WaitN.
  251. // maxFutureReserve specifies the maximum reservation wait duration allowed.
  252. // reserveN returns Reservation, not *Reservation, to avoid allocation in AllowN and WaitN.
  253. func (lim *Limiter) reserveN(now time.Time, n int, maxFutureReserve time.Duration) Reservation {
  254. lim.mu.Lock()
  255. defer lim.mu.Unlock()
  256. if lim.limit == Inf {
  257. return Reservation{
  258. ok: true,
  259. lim: lim,
  260. tokens: n,
  261. timeToAct: now,
  262. }
  263. }
  264. now, last, tokens := lim.advance(now)
  265. // Calculate the remaining number of tokens resulting from the request.
  266. tokens -= float64(n)
  267. // Calculate the wait duration
  268. var waitDuration time.Duration
  269. if tokens < 0 {
  270. waitDuration = lim.limit.durationFromTokens(-tokens)
  271. }
  272. // Decide result
  273. ok := n <= lim.burst && waitDuration <= maxFutureReserve
  274. // Prepare reservation
  275. r := Reservation{
  276. ok: ok,
  277. lim: lim,
  278. limit: lim.limit,
  279. }
  280. if ok {
  281. r.tokens = n
  282. r.timeToAct = now.Add(waitDuration)
  283. }
  284. // Update state
  285. if ok {
  286. lim.last = now
  287. lim.tokens = tokens
  288. lim.lastEvent = r.timeToAct
  289. } else {
  290. lim.last = last
  291. }
  292. return r
  293. }
  294. // advance calculates and returns an updated state for lim resulting from the passage of time.
  295. // lim is not changed.
  296. func (lim *Limiter) advance(now time.Time) (newNow time.Time, newLast time.Time, newTokens float64) {
  297. last := lim.last
  298. if now.Before(last) {
  299. last = now
  300. }
  301. // Avoid making delta overflow below when last is very old.
  302. maxElapsed := lim.limit.durationFromTokens(float64(lim.burst) - lim.tokens)
  303. elapsed := now.Sub(last)
  304. if elapsed > maxElapsed {
  305. elapsed = maxElapsed
  306. }
  307. // Calculate the new number of tokens, due to time that passed.
  308. delta := lim.limit.tokensFromDuration(elapsed)
  309. tokens := lim.tokens + delta
  310. if burst := float64(lim.burst); tokens > burst {
  311. tokens = burst
  312. }
  313. return now, last, tokens
  314. }
  315. // durationFromTokens is a unit conversion function from the number of tokens to the duration
  316. // of time it takes to accumulate them at a rate of limit tokens per second.
  317. func (limit Limit) durationFromTokens(tokens float64) time.Duration {
  318. seconds := tokens / float64(limit)
  319. return time.Nanosecond * time.Duration(1e9*seconds)
  320. }
  321. // tokensFromDuration is a unit conversion function from a time duration to the number of tokens
  322. // which could be accumulated during that duration at a rate of limit tokens per second.
  323. func (limit Limit) tokensFromDuration(d time.Duration) float64 {
  324. return d.Seconds() * float64(limit)
  325. }

雖然在某些情況下使用單個全域性速率限制器非常有用,但另一種常見情況是基於IP地址或API金鑰等識別符號為每個使用者實施速率限制器。我們將使用IP地址作為識別符號。簡單實現程式碼如下:

  1. package main
  2. import (
  3. "net/http"
  4. "sync"
  5. "time"
  6. "golang.org/x/time/rate"
  7. )
  8. // Create a custom visitor struct which holds the rate limiter for each
  9. // visitor and the last time that the visitor was seen.
  10. type visitor struct {
  11. limiter *rate.Limiter
  12. lastSeen time.Time
  13. }
  14. // Change the the map to hold values of the type visitor.
  15. var visitors = make(map[string]*visitor)
  16. var mtx sync.Mutex
  17. // Run a background goroutine to remove old entries from the visitors map.
  18. func init() {
  19. go cleanupVisitors()
  20. }
  21. func addVisitor(ip string) *rate.Limiter {
  22. limiter := rate.NewLimiter(2, 5)
  23. mtx.Lock()
  24. // Include the current time when creating a new visitor.
  25. visitors[ip] = &visitor{limiter, time.Now()}
  26. mtx.Unlock()
  27. return limiter
  28. }
  29. func getVisitor(ip string) *rate.Limiter {
  30. mtx.Lock()
  31. v, exists := visitors[ip]
  32. if !exists {
  33. mtx.Unlock()
  34. return addVisitor(ip)
  35. }
  36. // Update the last seen time for the visitor.
  37. v.lastSeen = time.Now()
  38. mtx.Unlock()
  39. return v.limiter
  40. }
  41. // Every minute check the map for visitors that haven't been seen for
  42. // more than 3 minutes and delete the entries.
  43. func cleanupVisitors() {
  44. for {
  45. time.Sleep(time.Minute)
  46. mtx.Lock()
  47. for ip, v := range visitors {
  48. if time.Now().Sub(v.lastSeen) > 3*time.Minute {
  49. delete(visitors, ip)
  50. }
  51. }
  52. mtx.Unlock()
  53. }
  54. }
  55. func limit(next http.Handler) http.Handler {
  56. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  57. limiter := getVisitor(r.RemoteAddr)
  58. if limiter.Allow() == false {
  59. http.Error(w, http.StatusText(429), http.StatusTooManyRequests)
  60. return
  61. }
  62. next.ServeHTTP(w, r)
  63. })
  64. }

轉載:https://blog.csdn.net/micl200110041/article/details/82013032