婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁 > 知識庫 > Go如何實現HTTP請求限流示例

Go如何實現HTTP請求限流示例

熱門標簽:汕頭小型外呼系統 惠州電銷防封電話卡 濱州自動電銷機器人排名 釘釘有地圖標注功能嗎 浙江高頻外呼系統多少錢一個月 鄭州亮點科技用的什么外呼系統 建造者2地圖標注 阿里云ai電話機器人 黃岡人工智能電銷機器人哪個好

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

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

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

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

好了我們先看Demo代碼的實現:

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

算法描述:

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

實現用戶粒度的限流

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

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

當然這只是一個簡單的實現方案,如果我們要在微服務的API-GateWay中去實現限流還是要考慮很多東西的。建議大家可以看看 https://github.com/didip/tollbooth 的源碼。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • Python+redis通過限流保護高并發系統
  • Redis和Lua實現分布式限流器的方法詳解
  • php使用lua+redis實現限流,計數器模式,令牌桶模式
  • 基于Redis的限流器的實現(示例講解)
  • 基于Redis實現分布式應用限流的方法
  • Golang實現請求限流的幾種辦法(小結)
  • go redis實現滑動窗口限流的方式(redis版)

標簽:駐馬店 阿壩 泰安 滄州 昭通 晉中 瀘州 東營

巨人網絡通訊聲明:本文標題《Go如何實現HTTP請求限流示例》,本文關鍵詞  如何,實現,HTTP,請求,限流,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《Go如何實現HTTP請求限流示例》相關的同類信息!
  • 本頁收集關于Go如何實現HTTP請求限流示例的相關信息資訊供網民參考!
  • 推薦文章
    婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av
    国产一区二区精品久久99| 一区二区三区中文免费| 欧美精品在线一区二区三区| 欧美国产精品一区二区| 亚洲线精品一区二区三区八戒| 偷拍一区二区三区| 99精品桃花视频在线观看| 国产女人aaa级久久久级| 日本欧美久久久久免费播放网| 欧美性受xxxx黑人xyx| 亚洲精品一二三四区| 99久久99久久精品国产片果冻| 国产亚洲一区二区三区在线观看| 国产乱码字幕精品高清av| 国产欧美日韩在线| 国产真实乱子伦精品视频| 337p亚洲精品色噜噜噜| 亚洲美女偷拍久久| 国产精品中文字幕日韩精品 | 亚洲成av人在线观看| 亚洲一区二区高清| 久久不见久久见中文字幕免费| 国产精品99久| 成人高清视频在线观看| 欧美日韩精品电影| 欧美一级二级在线观看| 国产亚洲精品久| 一区二区三区高清| 久色婷婷小香蕉久久| 不卡影院免费观看| 欧美视频一区二区| 欧美精品一区二区在线播放 | 国产丶欧美丶日本不卡视频| 欧美做爰猛烈大尺度电影无法无天| 日韩欧美成人一区二区| 国产精品网站导航| 亚洲综合图片区| 大桥未久av一区二区三区中文| 一本在线高清不卡dvd| 日韩一区二区三区av| 夜夜嗨av一区二区三区四季av | 紧缚奴在线一区二区三区| 国产一区二区三区四区五区美女 | 国产一区 二区| 欧美性色黄大片| 专区另类欧美日韩| 久久久精品天堂| 一区二区三区欧美日韩| 成人av资源下载| 国产欧美一区二区三区网站| 黑人巨大精品欧美黑白配亚洲| 欧美精品第1页| 无吗不卡中文字幕| 欧美三级电影网| 亚洲韩国精品一区| 欧美色大人视频| 亚洲第一综合色| 欧美一级xxx| 久久精品久久久精品美女| 欧美一区二区三区视频| 蜜臀av性久久久久蜜臀aⅴ| 国产精品一色哟哟哟| 国产精品久久久久久久浪潮网站| 韩国精品主播一区二区在线观看| 国产一区999| 国产精品久久久久久久蜜臀| 99国产精品视频免费观看| 亚洲天堂2014| 欧美精品日韩一区| 国产一区二区精品久久99| 久久精品一区二区三区四区| 高清成人在线观看| 亚洲一本大道在线| 欧美精品乱人伦久久久久久| 国内精品伊人久久久久av一坑 | 91精品国产一区二区三区| 亚洲一区免费视频| 欧美三级韩国三级日本三斤| 日本欧美韩国一区三区| 国产盗摄一区二区| 亚洲va韩国va欧美va| 久久精品夜夜夜夜久久| 免费成人在线影院| 久久精品一区二区三区不卡 | 国产成人免费av在线| 亚洲私人影院在线观看| 欧美高清视频在线高清观看mv色露露十八 | 青青草原综合久久大伊人精品优势| 欧美色欧美亚洲另类二区| 亚洲bt欧美bt精品| 亚洲欧洲精品一区二区三区| 国产一区二区女| 亚洲黄色尤物视频| 欧美国产激情二区三区| 欧美视频一区二区三区在线观看 | av成人动漫在线观看| 91麻豆国产福利精品| 日韩电影一区二区三区四区| 日韩国产精品91| 国产农村妇女毛片精品久久麻豆| 国产精品免费丝袜| 亚洲女人的天堂| 久久午夜电影网| 精品国产乱码91久久久久久网站| 99re视频这里只有精品| 欧美丝袜第三区| 色婷婷久久一区二区三区麻豆| 亚洲欧美日韩国产另类专区| 日本一区二区三区dvd视频在线| 亚洲综合在线视频| 国产最新精品精品你懂的| 欧美三级中文字| 久久精品999| 成人午夜av影视| 欧美肥胖老妇做爰| 久久精品国产在热久久| 91精彩视频在线观看| 亚洲成人自拍一区| 在线观看区一区二| 男女男精品视频网| 欧美电影在线免费观看| 精品少妇一区二区三区日产乱码| 欧美在线制服丝袜| 亚洲综合在线免费观看| 一区二区三区在线视频播放| 91精品婷婷国产综合久久性色| 亚洲欧洲精品天堂一级| 久久综合久色欧美综合狠狠| 欧美日韩亚洲综合在线| 91在线播放网址| 婷婷激情综合网| 波多野结衣精品在线| 欧美色图片你懂的| 高清不卡在线观看| 天堂一区二区在线| 国产精品久久久久久久久免费樱桃 | 中文字幕av不卡| 亚洲精品国产精华液| 成人教育av在线| 日韩欧美国产一区二区三区 | 麻豆久久久久久久| 精品国精品自拍自在线| 亚洲综合成人在线视频| 久久疯狂做爰流白浆xx| 亚洲欧美日韩一区二区三区在线观看| 成人综合激情网| 国产免费成人在线视频| 亚洲综合偷拍欧美一区色| 欧美激情在线看| 97久久精品人人爽人人爽蜜臀| 国产精品免费免费| 久久国产尿小便嘘嘘| 狠狠色狠狠色综合| 婷婷成人综合网| 蜜臀精品一区二区三区在线观看 | 美女脱光内衣内裤视频久久网站| 精品女同一区二区| 天天影视涩香欲综合网| 欧美色爱综合网| 成人av网址在线观看| 视频一区二区三区入口| 丰满岳乱妇一区二区三区| 日韩一区二区免费高清| 91精品麻豆日日躁夜夜躁| 国产精品第五页| 蜜桃久久av一区| 制服丝袜亚洲色图| 在线视频国内一区二区| 成人国产在线观看| 国产精品69毛片高清亚洲| 日韩女优电影在线观看| 色哟哟亚洲精品| 日韩精品中文字幕在线不卡尤物| 欧洲精品中文字幕| 美女视频一区在线观看| 国产成人在线电影| 91成人免费在线视频| 色综合激情五月| 亚洲一区二区黄色| 青娱乐精品视频在线| 麻豆国产91在线播放| 91精品国产品国语在线不卡| 欧美色成人综合| 丝袜a∨在线一区二区三区不卡| 狠狠色丁香久久婷婷综合丁香| 国产免费观看久久| 国产又粗又猛又爽又黄91精品| 91久久久免费一区二区| 成人精品一区二区三区中文字幕| 国产91高潮流白浆在线麻豆 | 欧美日韩一区二区三区高清| 青青草97国产精品免费观看无弹窗版| 成人av资源在线| 中文字幕 久热精品 视频在线| 日韩美女视频19| 欧美午夜精品理论片a级按摩| 中文字幕免费在线观看视频一区| 欧美二区三区91| 精品一区二区三区香蕉蜜桃| www国产亚洲精品久久麻豆|