成人性生交大片免费看视频r_亚洲综合极品香蕉久久网_在线视频免费观看一区_亚洲精品亚洲人成人网在线播放_国产精品毛片av_久久久久国产精品www_亚洲国产一区二区三区在线播_日韩一区二区三区四区区区_亚洲精品国产无套在线观_国产免费www

主頁 > 知識(shí)庫 > Golang實(shí)現(xiàn)請(qǐng)求限流的幾種辦法(小結(jié))

Golang實(shí)現(xiàn)請(qǐng)求限流的幾種辦法(小結(jié))

熱門標(biāo)簽:濮陽自動(dòng)外呼系統(tǒng)代理 賺地圖標(biāo)注的錢犯法嗎 智能電銷機(jī)器人營銷 長沙ai機(jī)器人電銷 烏魯木齊人工電銷機(jī)器人系統(tǒng) 廣東語音外呼系統(tǒng)供應(yīng)商 澳門防封電銷卡 地圖標(biāo)注測(cè)試 福州鐵通自動(dòng)外呼系統(tǒng)

在開發(fā)高并發(fā)系統(tǒng)時(shí),有三把利器用來保護(hù)系統(tǒng):緩存、降級(jí)和限流。那么何為限流呢?顧名思義,限流就是限制流量,就像你寬帶包了1個(gè)G的流量,用完了就沒了。

簡單的并發(fā)控制

利用 channel 的緩沖設(shè)定,我們就可以來實(shí)現(xiàn)并發(fā)的限制。我們只要在執(zhí)行并發(fā)的同時(shí),往一個(gè)帶有緩沖的 channel 里寫入點(diǎn)東西(隨便寫啥,內(nèi)容不重要)。讓并發(fā)的 goroutine在執(zhí)行完成后把這個(gè) channel 里的東西給讀走。這樣整個(gè)并發(fā)的數(shù)量就講控制在這個(gè) channel的緩沖區(qū)大小上。

比如我們可以用一個(gè) bool 類型的帶緩沖 channel 作為并發(fā)限制的計(jì)數(shù)器。

chLimit := make(chan bool, 1)

然后在并發(fā)執(zhí)行的地方,每創(chuàng)建一個(gè)新的 goroutine,都往 chLimit 里塞個(gè)東西。

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

這里通過 go 關(guān)鍵字并發(fā)執(zhí)行的是新構(gòu)造的函數(shù)。他在執(zhí)行完后,會(huì)把 chLimit的緩沖區(qū)里給消費(fèi)掉一個(gè)。

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

這樣一來,當(dāng)創(chuàng)建的 goroutine 數(shù)量到達(dá) chLimit 的緩沖區(qū)上限后。主 goroutine 就掛起阻塞了,直到這些 goroutine 執(zhí)行完畢,消費(fèi)掉了 chLimit 緩沖區(qū)中的數(shù)據(jù),程序才會(huì)繼續(xù)創(chuàng)建新的 goroutine 。我們并發(fā)數(shù)量限制的目的也就達(dá)到了。

例子

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

運(yùn)行結(jié)果:

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

如果修改并發(fā)限制為2:

chLimit := make(chan bool, 2)

運(yùn)行結(jié)果:

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

使用計(jì)數(shù)器實(shí)現(xiàn)請(qǐng)求限流

限流的要求是在指定的時(shí)間間隔內(nèi),server 最多只能服務(wù)指定數(shù)量的請(qǐng)求。實(shí)現(xiàn)的原理是我們啟動(dòng)一個(gè)計(jì)數(shù)器,每次服務(wù)請(qǐng)求會(huì)把計(jì)數(shù)器加一,同時(shí)到達(dá)指定的時(shí)間間隔后會(huì)把計(jì)數(shù)器清零;這個(gè)計(jì)數(shù)器的實(shí)現(xiàn)代碼如下所示:

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
}

在服務(wù)請(qǐng)求的時(shí)候, 我們會(huì)對(duì)當(dāng)前計(jì)數(shù)器和閾值進(jìn)行比較,只有未超過閾值時(shí)才進(jìn)行服務(wù):

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官方包實(shí)現(xiàn)httpserver頻率限制

使用golang來編寫httpserver時(shí),可以使用官方已經(jīng)有實(shí)現(xiàn)好的包:

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 ),基本思路就是為連接數(shù)計(jì)數(shù),通過make chan來建立一個(gè)最大連接數(shù)的channel, 每次accept就+1,close時(shí)候就-1. 當(dāng)?shù)竭_(dá)最大連接數(shù)時(shí),就等待空閑連接出來之后再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滿了,就會(huì)阻塞在這
  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時(shí)釋放占用的sem
  l.releaseOnce.Do(l.release)
  return err
}

使用Token Bucket(令牌桶算法)實(shí)現(xiàn)請(qǐng)求限流

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

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

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

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

實(shí)現(xiàn)

// 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 {
  //maximum token, token num per second
  limit Limit
  //burst field, max token num
  burst int
  mu  sync.Mutex
  //tokens num, change
  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
  //This is the time to action
  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(163 - 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)
}

雖然在某些情況下使用單個(gè)全局速率限制器非常有用,但另一種常見情況是基于IP地址或API密鑰等標(biāo)識(shí)符為每個(gè)用戶實(shí)施速率限制器。我們將使用IP地址作為標(biāo)識(shí)符。簡單實(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)
  })
}

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

您可能感興趣的文章:
  • golang簡易令牌桶算法實(shí)現(xiàn)代碼
  • 詳解Golang實(shí)現(xiàn)請(qǐng)求限流的幾種辦法
  • golang高并發(fā)限流操作 ping / telnet
  • golang接口IP限流,IP黑名單,IP白名單的實(shí)例
  • Golang 限流器的使用和實(shí)現(xiàn)示例
  • Golang模擬令牌桶進(jìn)行對(duì)訪問的限流方式

標(biāo)簽:德州 慶陽 廣西 阿克蘇 西雙版納 貴陽 調(diào)研邀請(qǐng) 太原

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Golang實(shí)現(xiàn)請(qǐng)求限流的幾種辦法(小結(jié))》,本文關(guān)鍵詞  Golang,實(shí)現(xiàn),請(qǐng)求,限,流的,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《Golang實(shí)現(xiàn)請(qǐng)求限流的幾種辦法(小結(jié))》相關(guān)的同類信息!
  • 本頁收集關(guān)于Golang實(shí)現(xiàn)請(qǐng)求限流的幾種辦法(小結(jié))的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    久久国产黄色片| 白浆视频在线观看| 成年人看的免费视频| 黄色在线资源| 91在线免费观看网站| 欧美又大粗又爽又黄大片视频| 波多野结衣之无限发射| 久久三级福利| 国产农村妇女aaaaa视频| 欧美三级视频| 91精品秘密在线观看| 日本成人午夜影院| 在线观看av资源网| 天天影视色香欲综合网天天录日日录| 久久免费成人精品视频| 免费高清视频在线观看| 日韩免费小视频| 亚洲免费不卡视频| 黑人乱码一区二区三区av| 黄网站在线免费| 亚洲不卡中文字幕无码| 亚洲美女在线视频| 亚洲精品久久久久久无码色欲四季| 性色av一区二区怡红| 99国产精品99久久久久久粉嫩| 夜夜嗨av一区二区三区四季av| 国产精品视频一区二区三区,| 日韩二区三区四区| 蜜臀久久99精品久久久| 国产欧美日韩综合一区在线播放| 91麻豆免费视频网站| 三上悠亚在线观看| 日韩精品在线免费视频| 中文字幕中文在线| 日本高清一区二区视频| 国产婷婷精品av在线| 亚洲先锋影音| 欧美精品一区二区性色a+v| 亚洲高清123| 九九热精彩视频| 欧美高清视频不卡网| 亚洲福利小视频| 国产高清在线观看免费不卡| 欧美成人a交片免费看| 亚洲小说区图片| av成人影院在线| 九热视频在线观看| 久久久久免费视频| 91黄色免费视频| 91蜜桃网站免费观看| 国产精品jizz视频| 成人激情免费在线| 国产视频一二区| 国产福利免费在线观看| 91av国产精品| 第四色男人最爱上成人网| 亚洲欧洲日产国码二区| 黄网站免费观看| 五月天婷婷激情| 国产精品乱码一区二区| 欧美少妇激情| 自拍偷拍精品| 销魂美女一区二区| 成人精品国产福利| 欧美国产一区二区在线观看| 国产精品久久久久婷婷二区次| 91精品综合久久| 亚洲午夜在线| a√天堂在线观看| 性插视频在线观看| 国产在线观看91精品一区| 极品裸体白嫩激情啪啪国产精品| 亚洲国产成人精品久久久国产成人一区| 久久99久久久久| 中文字幕日韩高清| 天天色综合天天色| 99re6在线精品视频免费播放| 国产aⅴ一区二区三区| 亚洲精品一区二区久| 久久天天久久| 偷窥少妇高潮呻吟av久久免费| 交换国产精品视频一区| 国产专区一区二区| 美女无遮挡网站| 一本色道久久88亚洲精品综合| 欧美精品二区| 日韩精品在线播放| 性xxxfllreexxx少妇| 久久中文字幕在线视频| 在线一区av| 九九视频精品全部免费播放| 亚洲字幕成人中文在线观看| 欧美一级视频免费观看| 精品国产人成亚洲区| 久久综合在线观看| 国产精品久久久久久久久影视| 久草在线免费二| 欧美边添边摸边做边爱免费| 久久人人爽人人爽| 在线精品国精品国产尤物884a| 国产又大又粗又硬| 伊人影院在线观看视频| 亚洲a级在线播放观看| 91久久精品一区二区| 久久午夜电影| 国产乱淫av片| 日韩欧美美女在线观看| 又黄又爽在线观看| 国内精品免费**视频| 欧美激情免费看| 亚洲国产另类av| 国产精品99久久久久久大便| 免费又黄又爽又猛大片午夜| 在线观看日本www| 综合激情一区| 国产99精品视频| 理论片午午伦夜理片在线播放| 粉嫩av一区二区三区在线播放| 国产亚洲精品一区二555| 免费a级黄色片| 亚洲成色777777女色窝| 色悠悠在线视频| 精品少妇一区二区三区日产乱码| 亚洲伦理网站| 亚洲精品一区二区毛豆| 国产成人精品视频免费看| 美女午夜精品| 国产高潮流白浆喷水视频| 免费污网站在线观看| 大片免费播放在线视频| 亚洲天堂在线播放| 裸体网站视频| 5858p先锋影音资源网| 成人毛片在线精品国产| 亚洲国产合集| 久久久久久免费看| 免费人成a大片在线观看动漫| 日本视频在线免费观看| 9国产精品午夜| 丝袜美腿亚洲一区| 中文字幕在线观看91| 91精品国产综合久久国产大片| 亚洲午夜未删减在线观看| 青青草原成人网| 久久99久久99精品免视看婷婷| 91九色蝌蚪成人| 黄色的视频在线观看| 狠狠色噜噜狠狠色综合久| 午夜一区二区视频| 欧美一区二区激情视频| 91精品国产高清91久久久久久| 日韩美女主播在线视频一区二区三区| 国产色产综合产在线视频| 欧美日韩a区| 欧美一级片在线免费观看| 触手亚洲一区二区三区| 国产美女视频一区二区| 日韩精品一区三区| 国产乱码在线| 日本三级视频在线播放| 亚洲无线码在线一区观看| 国产精品男人爽免费视频1| 色视频在线免费观看| 成人午夜在线视频| 久久亚洲精品国产| 亚洲欧洲中文日韩久久av乱码| 国产露脸无套对白在线播放| 国产麻豆综合| 久久激情网站| 成人国产精品一区二区| 成人综合国产精品| zzijzzij亚洲日本成熟少妇| 久久精品国产**网站演员| 久久99精品久久只有精品| 欧美性感一区二区三区| 91精品国产综合久久福利| 国产xxx在线| 老师我好爽再深一点的视频| 伊人春色在线观看| 中文字幕在线播| 免费看一区二区三区| 91精品人妻一区二区三区果冻| 96pao国产成视频永久免费| 国产又粗又猛又爽又黄91精品| 久久蜜桃av一区精品变态类天堂| 欧美日韩爱爱| 天堂中文字幕在线观看| 亚洲一区二区高清| 久久精品人人做| 超碰在线观看av| 欧美中文字幕久久| 91精品久久久久久久久久久| 免费av毛片在线看| 国产精品丝袜高跟| 成人免费毛片嘿嘿连载视频…| 自拍另类欧美| 激情综合亚洲| 精品亚洲成人| 特级西西人体4444xxxx| 日韩综合中文字幕| www.国产一区| 天天射天天色天天干| 日韩中文字幕一区二区| 日韩毛片在线免费观看| 99在线精品视频| 激情亚洲小说| 欧美日韩精品免费观看视欧美高清免费大片| 四虎在线免费观看| 国产传媒一区| 亚洲综合一区二区不卡| 欧美成人免费全部网站| 久久久亚洲精品无码| 午夜啪啪免费视频| 欧美日韩亚洲一二三| 精品久久久久久久久久久久久久久久| 亚洲一区精品电影| 亚洲一二三专区| 天堂av资源在线观看| 成人免费福利| 日韩精品无码一区二区三区| 成人黄色在线看| 久久精品盗摄| 天天影视久久综合| 国产福利精品一区| 猫咪av网站| 国产福利一区二区三区在线视频| 99九九精品视频| 黄网在线观看视频| 欧美日韩高清丝袜| 一卡二卡3卡四卡高清精品视频| 色悠悠国产精品| 久久国产精品亚洲人一区二区三区| 中文字幕亚洲欧美一区二区三区| 日本a级在线| 天天久久综合| 欧美网站在线观看| 青草青在线视频| 日本韩国精品一区二区| 成人h视频在线观看播放| 91美女片黄在线| 中文字幕国产精品| 国产精品自拍偷拍| 亚洲一区二区三区午夜| 国产视频久久| 久久久夜色精品| 日韩免费电影一区二区| 在线看成人短视频| 少妇真人直播免费视频| 国产91精品网站| 欧美日韩一区二区三区免费| 天涯成人国产亚洲精品一区av| 五级黄高潮片90分钟视频| 一区二区av在线| 99精品欧美| www.18av.com| 成人高清伦理免费影院在线观看| 在线黄色的网站| 午夜精品一区二区三区在线| 国产又白又嫩又紧又爽18p| 日韩av男人的天堂| 日韩精品电影网站| 精品一二三四五区| 国产一区二区自拍视频| bbw在线视频| 国产盗摄一区二区三区| 久久久久狠狠高潮亚洲精品| 丁香花免费高清完整在线播放| 美女一区二区三区| 欧美中文字幕在线观看视频| 无码人妻熟妇av又粗又大| 欧美极品色图| 91在线导航| 老太脱裤让老头玩ⅹxxxx| 男人天堂av在线播放| 美女毛片一区二区三区四区| 国产精品极品美女在线观看免费| 亚洲精品成a人ⅴ香蕉片| 日本黄色不卡视频| 99久久精品99国产精品| 日本xxxxxxx免费视频| 国产毛片毛片毛片毛片毛片| 一区二区日韩视频| 成人在线免费播放视频| 在线观看日本一区二区| 2020日本不卡一区二区视频| 手机看片福利永久| 欧美高清电影在线看| 亚洲国产精品狼友在线观看| 国产精品日韩av| 日韩欧美一区二区三区久久| 日韩免费电影网站| 免费在线观看日韩视频| 亚洲成人精品综合在线| 91国产丝袜在线放| 日韩福利电影在线| 999亚洲国产精| 成人午夜电影在线观看| 天堂…中文在线最新版在线| 亚洲麻豆一区二区三区| 日本在线一区二区三区| 成人18视频在线观看| 欧美日韩精品一区二区三区四区| 成人精品3d动漫| 天堂网www中文在线| 蜜月aⅴ免费一区二区三区| 蜜桃传媒一区二区亚洲| 91丨国产丨九色丨pron| 欧美bbxxx| 日本一区二区欧美| 欧美精品亚洲精品日韩精品| 欧美日韩偷拍视频| 色综合欧美在线| 日本免费一区二区三区| 午夜免费福利网站| 成人福利视频网站| free性欧美| 亚洲av无码乱码在线观看性色| 国产精品久久国产| 奇米影视狠888| 国产精品久久综合av爱欲tv| av在线麻豆| 成人国产精品久久久网站| 久久视频在线视频| 国产一区欧美一区| 国产全是老熟女太爽了| 亚洲天堂黄色片| 日本波多野结衣在线| jizz亚洲|