欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Go如何實(shí)現(xiàn)HTTP請(qǐng)求限流示例

 更新時(shí)間:2018年04月19日 14:34:10   作者:謝權(quán)''SELF  
本篇文章主要介紹了Go如何實(shí)現(xiàn)HTTP請(qǐng)求限流示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

在開發(fā)高并發(fā)系統(tǒng)時(shí)有三把利器用來(lái)保護(hù)系統(tǒng):緩存、降級(jí)和限流!為了保證在業(yè)務(wù)高峰期,線上系統(tǒng)也能保證一定的彈性和穩(wěn)定性,最有效的方案就是進(jìn)行服務(wù)降級(jí)了,而限流就是降級(jí)系統(tǒng)最常采用的方案之一。

這里為大家推薦一個(gè)開源庫(kù) https://github.com/didip/tollbooth 但是,如果您想要一些簡(jiǎn)單的、輕量級(jí)的或者只是想要學(xué)習(xí)的東西,實(shí)現(xiàn)自己的中間件來(lái)處理速率限制并不困難。今天我們就來(lái)聊聊如何實(shí)現(xiàn)自己的一個(gè)限流中間件

首先我們需要安裝一個(gè)提供了 Token bucket (令牌桶算法)的依賴包,上面提到的toolbooth 的實(shí)現(xiàn)也是基于它實(shí)現(xiàn)的

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

好了我們先看Demo代碼的實(shí)現(xiàn):

limit.go

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)
  })
}

main.go

package main

import (
  "net/http"
)

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"))
}

我們看看 rate.NewLimiter的源碼:

// 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.
// Most callers should use Wait.
//
// Each of the three methods consumes a single token.
// They differ in their behavior when no token is available.
// If no token is available, Allow returns false.
// If no token is available, Reserve returns a reservation for a future token
// and the amount of time the caller must wait before using it.
// If no token is available, Wait blocks until one can be obtained
// or its associated context.Context is canceled.
//
// The methods AllowN, ReserveN, and WaitN consume n tokens.
type Limiter struct {
 limit Limit
 burst int

 mu   sync.Mutex
 tokens float64
 // last is the last time the limiter's tokens field was updated
 last time.Time
 // lastEvent is the latest time of a rate-limited event (past or future)
 lastEvent time.Time
}

// Limit returns the maximum overall event rate.
func (lim *Limiter) Limit() Limit {
 lim.mu.Lock()
 defer lim.mu.Unlock()
 return lim.limit
}

// Burst returns the maximum burst size. Burst is the maximum number of tokens
// that can be consumed in a single call to Allow, Reserve, or Wait, so higher
// Burst values allow more events to happen at once.
// A zero Burst allows no events, unless limit == Inf.
func (lim *Limiter) Burst() int {
 return lim.burst
}

// NewLimiter returns a new Limiter that allows events up to rate r and permits
// bursts of at most b tokens.
func NewLimiter(r Limit, b int) *Limiter {
 return &Limiter{
  limit: r,
  burst: b,
 }
}

// Allow is shorthand for AllowN(time.Now(), 1).
func (lim *Limiter) Allow() bool {
 return lim.AllowN(time.Now(), 1)
}

// AllowN reports whether n events may happen at time now.
// Use this method if you intend to drop / skip events that exceed the rate limit.
// Otherwise use Reserve or Wait.
func (lim *Limiter) AllowN(now time.Time, n int) bool {
 return lim.reserveN(now, n, 0).ok
}

// A Reservation holds information about events that are permitted by a Limiter to happen after a delay.
// A Reservation may be canceled, which may enable the Limiter to permit additional events.
type Reservation struct {
 ok    bool
 lim    *Limiter
 tokens  int
 timeToAct time.Time
 // This is the Limit at reservation time, it can change later.
 limit Limit
}

// OK returns whether the limiter can provide the requested number of tokens
// within the maximum wait time. If OK is false, Delay returns InfDuration, and
// Cancel does nothing.
func (r *Reservation) OK() bool {
 return r.ok
}

// Delay is shorthand for DelayFrom(time.Now()).
func (r *Reservation) Delay() time.Duration {
 return r.DelayFrom(time.Now())
}

// InfDuration is the duration returned by Delay when a Reservation is not OK.
const InfDuration = time.Duration(1<<63 - 1)

// DelayFrom returns the duration for which the reservation holder must wait
// before taking the reserved action. Zero duration means act immediately.
// InfDuration means the limiter cannot grant the tokens requested in this
// Reservation within the maximum wait time.
func (r *Reservation) DelayFrom(now time.Time) time.Duration {
 if !r.ok {
  return InfDuration
 }
 delay := r.timeToAct.Sub(now)
 if delay < 0 {
  return 0
 }
 return delay
}

// Cancel is shorthand for CancelAt(time.Now()).
func (r *Reservation) Cancel() {
 r.CancelAt(time.Now())
 return
}

// CancelAt indicates that the reservation holder will not perform the reserved action
// and reverses the effects of this Reservation on the rate limit as much as possible,
// considering that other reservations may have already been made.
func (r *Reservation) CancelAt(now time.Time) {
 if !r.ok {
  return
 }

 r.lim.mu.Lock()
 defer r.lim.mu.Unlock()

 if r.lim.limit == Inf || r.tokens == 0 || r.timeToAct.Before(now) {
  return
 }

 // calculate tokens to restore
 // The duration between lim.lastEvent and r.timeToAct tells us how many tokens were reserved
 // after r was obtained. These tokens should not be restored.
 restoreTokens := float64(r.tokens) - r.limit.tokensFromDuration(r.lim.lastEvent.Sub(r.timeToAct))
 if restoreTokens <= 0 {
  return
 }
 // advance time to now
 now, _, tokens := r.lim.advance(now)
 // calculate new number of tokens
 tokens += restoreTokens
 if burst := float64(r.lim.burst); tokens > burst {
  tokens = burst
 }
 // update state
 r.lim.last = now
 r.lim.tokens = tokens
 if r.timeToAct == r.lim.lastEvent {
  prevEvent := r.timeToAct.Add(r.limit.durationFromTokens(float64(-r.tokens)))
  if !prevEvent.Before(now) {
   r.lim.lastEvent = prevEvent
  }
 }

 return
}

// Reserve is shorthand for ReserveN(time.Now(), 1).
func (lim *Limiter) Reserve() *Reservation {
 return lim.ReserveN(time.Now(), 1)
}

// ReserveN returns a Reservation that indicates how long the caller must wait before n events happen.
// The Limiter takes this Reservation into account when allowing future events.
// ReserveN returns false if n exceeds the Limiter's burst size.
// Usage example:
//  r, ok := lim.ReserveN(time.Now(), 1)
//  if !ok {
//   // Not allowed to act! Did you remember to set lim.burst to be > 0 ?
//  }
//  time.Sleep(r.Delay())
//  Act()
// Use this method if you wish to wait and slow down in accordance with the rate limit without dropping events.
// If you need to respect a deadline or cancel the delay, use Wait instead.
// To drop or skip events exceeding rate limit, use Allow instead.
func (lim *Limiter) ReserveN(now time.Time, n int) *Reservation {
 r := lim.reserveN(now, n, InfDuration)
 return &r
}

// Wait is shorthand for WaitN(ctx, 1).
func (lim *Limiter) Wait(ctx context.Context) (err error) {
 return lim.WaitN(ctx, 1)
}

// WaitN blocks until lim permits n events to happen.
// It returns an error if n exceeds the Limiter's burst size, the Context is
// canceled, or the expected wait time exceeds the Context's Deadline.
func (lim *Limiter) WaitN(ctx context.Context, n int) (err error) {
 if n > lim.burst {
  return fmt.Errorf("rate: Wait(n=%d) exceeds limiter's burst %d", n, lim.burst)
 }
 // Check if ctx is already cancelled
 select {
 case <-ctx.Done():
  return ctx.Err()
 default:
 }
 // Determine wait limit
 now := time.Now()
 waitLimit := InfDuration
 if deadline, ok := ctx.Deadline(); ok {
  waitLimit = deadline.Sub(now)
 }
 // Reserve
 r := lim.reserveN(now, n, waitLimit)
 if !r.ok {
  return fmt.Errorf("rate: Wait(n=%d) would exceed context deadline", n)
 }
 // Wait
 t := time.NewTimer(r.DelayFrom(now))
 defer t.Stop()
 select {
 case <-t.C:
  // We can proceed.
  return nil
 case <-ctx.Done():
  // Context was canceled before we could proceed. Cancel the
  // reservation, which may permit other events to proceed sooner.
  r.Cancel()
  return ctx.Err()
 }
}

// SetLimit is shorthand for SetLimitAt(time.Now(), newLimit).
func (lim *Limiter) SetLimit(newLimit Limit) {
 lim.SetLimitAt(time.Now(), newLimit)
}

// SetLimitAt sets a new Limit for the limiter. The new Limit, and Burst, may be violated
// or underutilized by those which reserved (using Reserve or Wait) but did not yet act
// before SetLimitAt was called.
func (lim *Limiter) SetLimitAt(now time.Time, newLimit Limit) {
 lim.mu.Lock()
 defer lim.mu.Unlock()

 now, _, tokens := lim.advance(now)

 lim.last = now
 lim.tokens = tokens
 lim.limit = newLimit
}

// reserveN is a helper method for AllowN, ReserveN, and WaitN.
// maxFutureReserve specifies the maximum reservation wait duration allowed.
// reserveN returns Reservation, not *Reservation, to avoid allocation in AllowN and WaitN.
func (lim *Limiter) reserveN(now time.Time, n int, maxFutureReserve time.Duration) Reservation {
 lim.mu.Lock()
 defer lim.mu.Unlock()

 if lim.limit == Inf {
  return Reservation{
   ok:    true,
   lim:    lim,
   tokens:  n,
   timeToAct: now,
  }
 }

 now, last, tokens := lim.advance(now)

 // Calculate the remaining number of tokens resulting from the request.
 tokens -= float64(n)

 // Calculate the wait duration
 var waitDuration time.Duration
 if tokens < 0 {
  waitDuration = lim.limit.durationFromTokens(-tokens)
 }

 // Decide result
 ok := n <= lim.burst && waitDuration <= maxFutureReserve

 // Prepare reservation
 r := Reservation{
  ok:  ok,
  lim:  lim,
  limit: lim.limit,
 }
 if ok {
  r.tokens = n
  r.timeToAct = now.Add(waitDuration)
 }

 // Update state
 if ok {
  lim.last = now
  lim.tokens = tokens
  lim.lastEvent = r.timeToAct
 } else {
  lim.last = last
 }

 return r
}

// advance calculates and returns an updated state for lim resulting from the passage of time.
// lim is not changed.
func (lim *Limiter) advance(now time.Time) (newNow time.Time, newLast time.Time, newTokens float64) {
 last := lim.last
 if now.Before(last) {
  last = now
 }

 // Avoid making delta overflow below when last is very old.
 maxElapsed := lim.limit.durationFromTokens(float64(lim.burst) - lim.tokens)
 elapsed := now.Sub(last)
 if elapsed > maxElapsed {
  elapsed = maxElapsed
 }

 // Calculate the new number of tokens, due to time that passed.
 delta := lim.limit.tokensFromDuration(elapsed)
 tokens := lim.tokens + delta
 if burst := float64(lim.burst); tokens > burst {
  tokens = burst
 }

 return now, last, tokens
}

// durationFromTokens is a unit conversion function from the number of tokens to the duration
// of time it takes to accumulate them at a rate of limit tokens per second.
func (limit Limit) durationFromTokens(tokens float64) time.Duration {
 seconds := tokens / float64(limit)
 return time.Nanosecond * time.Duration(1e9*seconds)
}

// tokensFromDuration is a unit conversion function from a time duration to the number of tokens
// which could be accumulated during that duration at a rate of limit tokens per second.
func (limit Limit) tokensFromDuration(d time.Duration) float64 {
 return d.Seconds() * float64(limit)
}

算法描述:

用戶配置的平均發(fā)送速率為r,則每隔1/r秒一個(gè)令牌被加入到桶中(每秒會(huì)有r個(gè)令牌放入桶中),桶中最多可以存放b個(gè)令牌。如果令牌到達(dá)時(shí)令牌桶已經(jīng)滿了,那么這個(gè)令牌會(huì)被丟棄;

實(shí)現(xiàn)用戶粒度的限流

雖然在某些情況下使用單個(gè)全局速率限制器非常有用,但另一種常見情況是基于IP地址或API密鑰等標(biāo)識(shí)符為每個(gè)用戶實(shí)施速率限制器。我們將使用IP地址作為標(biāo)識(shí)符。簡(jiǎn)單實(shí)現(xiàn)代碼如下:

package main
import (
  "net/http"
  "sync"
  "time"

  "golang.org/x/time/rate"
)

// Create a custom visitor struct which holds the rate limiter for each
// visitor and the last time that the visitor was seen.
type visitor struct {
  limiter *rate.Limiter
  lastSeen time.Time
}

// Change the the map to hold values of the type visitor.
var visitors = make(map[string]*visitor)
var mtx sync.Mutex
// Run a background goroutine to remove old entries from the visitors map.
func init() {
  go cleanupVisitors()
}

func addVisitor(ip string) *rate.Limiter {
  limiter := rate.NewLimiter(2, 5)
  mtx.Lock()
  // Include the current time when creating a new visitor.
  visitors[ip] = &visitor{limiter, time.Now()}
  mtx.Unlock()
  return limiter
}

func getVisitor(ip string) *rate.Limiter {
  mtx.Lock()
  v, exists := visitors[ip]
  if !exists {
    mtx.Unlock()
    return addVisitor(ip)
  }
  // Update the last seen time for the visitor.
  v.lastSeen = time.Now()
  mtx.Unlock()
  return v.limiter
}

// Every minute check the map for visitors that haven't been seen for
// more than 3 minutes and delete the entries.
func cleanupVisitors() {
  for {
    time.Sleep(time.Minute)
    mtx.Lock()
    for ip, v := range visitors {
      if time.Now().Sub(v.lastSeen) > 3*time.Minute {
        delete(visitors, ip)
      }
    }
    mtx.Unlock()
  }
}

func limit(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    limiter := getVisitor(r.RemoteAddr)
    if limiter.Allow() == false {
      http.Error(w, http.StatusText(429), http.StatusTooManyRequests)
      return
    }
    next.ServeHTTP(w, r)
  })
}

當(dāng)然這只是一個(gè)簡(jiǎn)單的實(shí)現(xiàn)方案,如果我們要在微服務(wù)的API-GateWay中去實(shí)現(xiàn)限流還是要考慮很多東西的。建議大家可以看看 https://github.com/didip/tollbooth 的源碼。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Golang函數(shù)式編程深入分析實(shí)例

    Golang函數(shù)式編程深入分析實(shí)例

    習(xí)慣與函數(shù)式編程語(yǔ)言的開發(fā)者,會(huì)認(rèn)為for循環(huán)和if判斷語(yǔ)句是冗長(zhǎng)的代碼,通過(guò)使用map和filter處理集合元素讓代碼更可讀。本文介紹Go閉包實(shí)現(xiàn)集合轉(zhuǎn)換和過(guò)濾功能
    2023-01-01
  • go中Excelize處理excel表實(shí)現(xiàn)帶數(shù)據(jù)校驗(yàn)的文件導(dǎo)出

    go中Excelize處理excel表實(shí)現(xiàn)帶數(shù)據(jù)校驗(yàn)的文件導(dǎo)出

    本文主要介紹了go中Excelize處理excel表實(shí)現(xiàn)帶數(shù)據(jù)校驗(yàn)的文件導(dǎo)出,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-06-06
  • 談?wù)刧olang的netpoll原理解析

    談?wù)刧olang的netpoll原理解析

    本文詳細(xì)介紹了Go語(yǔ)言中netpoll部分的實(shí)現(xiàn)細(xì)節(jié)和協(xié)程阻塞調(diào)度原理,特別是epoll在Linux環(huán)境下的工作原理,Go語(yǔ)言通過(guò)將epoll操作放在runtime包中,結(jié)合運(yùn)行時(shí)調(diào)度功能,實(shí)現(xiàn)了高效的協(xié)程I/O操作,感興趣的朋友跟隨小編一起看看吧
    2024-11-11
  • Go中各種newreader和newbuffer的使用總結(jié)

    Go中各種newreader和newbuffer的使用總結(jié)

    這篇文章主要為大家詳細(xì)介紹了Go語(yǔ)言中各種newreader和newbuffer的使用的相關(guān)資料,文中的示例代碼講解詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴可以了解下
    2023-11-11
  • 利用systemd部署golang項(xiàng)目的實(shí)現(xiàn)方法

    利用systemd部署golang項(xiàng)目的實(shí)現(xiàn)方法

    這篇文章主要介紹了利用systemd部署golang項(xiàng)目的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • 一文帶你掌握Golang中panic與recover的使用方法

    一文帶你掌握Golang中panic與recover的使用方法

    這篇文章主要介紹了Golang中panic與recover的作用和使用方法,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,需要的小伙伴可以參考一下
    2023-04-04
  • Go Java算法之同構(gòu)字符串示例詳解

    Go Java算法之同構(gòu)字符串示例詳解

    這篇文章主要為大家介紹了Go Java算法之同構(gòu)字符串示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-08-08
  • 詳解Go channel管道的運(yùn)行原理

    詳解Go channel管道的運(yùn)行原理

    Go推薦通過(guò)通信來(lái)共享內(nèi)存,而channel就實(shí)現(xiàn)了這一理念。那channel是怎么運(yùn)行的呢?本文將帶你搞懂Go channel管道的運(yùn)行原理,感興趣的同學(xué)可以參考一下
    2023-05-05
  • Golang中Gin框架的使用入門教程

    Golang中Gin框架的使用入門教程

    這篇文章主要為大家詳細(xì)介紹了Golang中Gin框架的使用教程,文中通過(guò)簡(jiǎn)單的示例為大家講解了Gin框架的安裝與使用,感興趣的小伙伴開業(yè)跟隨小編一起學(xué)習(xí)一下
    2022-10-10
  • 一文詳解Golang中consul的基本使用

    一文詳解Golang中consul的基本使用

    consul是一個(gè)開源服務(wù)注冊(cè)和服務(wù)發(fā)現(xiàn)的中心,可以用于微服務(wù)的注冊(cè)和服務(wù)之間的調(diào)用的發(fā)現(xiàn),幫助上游服務(wù)找到下游服務(wù)的具體ip:port或者是domain,也可以使用dns的方式讓consul幫你去做轉(zhuǎn)發(fā)。本文就來(lái)講講它的具體使用吧
    2023-03-03

最新評(píng)論