Go 基于令牌桶的限流器實(shí)現(xiàn)
簡(jiǎn)介
如果一般流量過(guò)大,下游系統(tǒng)反應(yīng)不過(guò)來(lái),這個(gè)時(shí)候就需要限流了,其實(shí)和上地鐵是一樣的,就是減慢上游訪(fǎng)問(wèn)下游的速度。
限制訪(fǎng)問(wèn)服務(wù)的頻次或者頻率,防止服務(wù)過(guò)載,被刷爆等。
Golang 官方擴(kuò)展包 time(golang.org/x/time/rate) 中,提供了一個(gè)基于令牌桶等限流器實(shí)現(xiàn)。
原理概述
- 令牌:每次拿到令牌,才可訪(fǎng)問(wèn)
- 桶 ,桶的最大容量是固定的,以固定的頻率向桶內(nèi)增加令牌,直至加滿(mǎn)
- 每個(gè)請(qǐng)求消耗一個(gè)令牌。
- 限流器初始化的時(shí)候,令牌桶一般是滿(mǎn)的。
具體使用
package limiter import ( "fmt" "testing" "time" "golang.org/x/time/rate" ) func TestLimter(t *testing.T) { limiter := rate.NewLimiter(rate.Every(time.Millisecond*31), 2) //time.Sleep(time.Second) for i := 0; i < 10; i++ { var ok bool if limiter.Allow() { ok = true } time.Sleep(time.Millisecond * 20) fmt.Println(ok, limiter.Burst()) } }
執(zhí)行結(jié)果:
=== RUN TestLimter
true 2
true 2
true 2
false 2
true 2
true 2
false 2
true 2
true 2
false 2
--- PASS: TestLimter (0.21s)
通過(guò)執(zhí)行結(jié)果可以看到, 令牌桶開(kāi)始是2個(gè)滿(mǎn)的,由于令牌的間隔比請(qǐng)求的間隔多了11ms(31-20), 所以每?jī)蓚€(gè)請(qǐng)求會(huì)失敗一次。
具體實(shí)現(xiàn)原理
先看下限流器的創(chuàng)建方法: NewLimiter
func NewLimiter(r Limit, b int) *Limiter { return &Limiter{ limit: r, burst: b, } }
查看限流器數(shù)據(jù)結(jié)構(gòu) Limiter
// The methods AllowN, ReserveN, and WaitN consume n tokens. type Limiter struct { mu sync.Mutex limit Limit burst int 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 }
- burst 表示了桶的大小
- limit 表示放入桶的頻率
- tokens 表示剩余令牌個(gè)數(shù)
- last 最近取走 token 的時(shí)間
- lastEvent 最近限流事件的時(shí)間
當(dāng)令牌桶發(fā)放后,會(huì)保留在 Reservation 對(duì)象中, 定義如下, Reservation 對(duì)象,描述了一個(gè)達(dá)到 timeToAct 時(shí)間后,可以獲取到的令牌的數(shù)量 tokens 數(shù)。
type Reservation struct { ok bool // 是否滿(mǎn)足條件分配到了tokens lim *Limiter // 發(fā)送令牌的限流器 tokens int // tokens 的數(shù)量 timeToAct time.Time // 滿(mǎn)足令牌發(fā)放的時(shí)間 limit Limit // 令牌發(fā)放速度 }
限流器如何限流
官方提供的限流器有阻塞等待, 也有直接判斷方式的, 還有提供維護(hù)預(yù)留式等。
如何實(shí)現(xiàn)限流的代碼,在 reserveN 中。
使用時(shí),每次都調(diào)用了 Allow() 方法
// 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 }
繼續(xù)查看 reserverN 算法
方法說(shuō)明:
- 三個(gè)參數(shù): now, n, maxFutureReserve
- 在 now 時(shí)間需要拿到 n 個(gè)令牌,最多等待的時(shí)間為 maxFutureReserve
- 結(jié)果將返回一個(gè)預(yù)留令牌的對(duì)象 Reservation
// 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() // 首先判斷是否放入頻次是否為無(wú)窮大,如果為無(wú)窮大,說(shuō)明暫時(shí)不限流 if lim.limit == Inf { lim.mu.Unlock() return Reservation{ ok: true, lim: lim, tokens: n, timeToAct: now, } } // 拿到截止 now 時(shí)間時(shí),可以獲取的令牌 tokens 數(shù)量,上一次拿走令牌的時(shí)間是last now, last, tokens := lim.advance(now) // Calculate the remaining number of tokens resulting from the request. // 更新 tokens數(shù)量,把需要拿走的去掉 tokens -= float64(n) // Calculate the wait duration // 如果 tokens 數(shù)量為負(fù)數(shù),說(shuō)明需要等待,計(jì)算等待時(shí)間 WaitDuration var waitDuration time.Duration if tokens < 0 { waitDuration = lim.limit.durationFromTokens(-tokens) } // Decide result // 計(jì)算是否滿(mǎn)足分配要求 // 1. 需要分配的大小不超過(guò)桶容量 // 2. 等待時(shí)間不超過(guò)設(shè)定的等待時(shí)長(zhǎng) ok := n <= lim.burst && waitDuration <= maxFutureReserve // Prepare reservation // 最后構(gòu)造一個(gè) Resvervation 對(duì)象 r := Reservation{ ok: ok, lim: lim, limit: lim.limit, } if ok { r.tokens = n r.timeToAct = now.Add(waitDuration) } // Update state // 需要更新當(dāng)前 limit 的值 if ok { lim.last = now lim.tokens = tokens lim.lastEvent = r.timeToAct } else { lim.last = last } lim.mu.Unlock() return r }
從實(shí)現(xiàn)上看, limiter 并不是每隔一段時(shí)間更新當(dāng)前桶的數(shù)量,而是記錄了上次訪(fǎng)問(wèn)時(shí)和當(dāng)前桶中令牌的數(shù)量,當(dāng)再次訪(fǎng)問(wèn)時(shí),通過(guò)上次訪(fǎng)問(wèn)時(shí)間計(jì)算出當(dāng)前令牌的數(shù)量,決定是否可以發(fā)放令牌。
到此這篇關(guān)于Go 基于令牌桶的限流器實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Go 令牌桶限流器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Golang channle管道的基本使用及快速入門(mén)
管道是Go語(yǔ)言中實(shí)現(xiàn)并發(fā)的一種方式,它可以在多個(gè)goroutine之間進(jìn)行通信和數(shù)據(jù)交換,本文主要介紹了Golang channle管道的基本使用及快速入門(mén),具有一定的參考價(jià)值,感興趣的可以了解一下2023-12-12golang使用json格式實(shí)現(xiàn)增刪查改的實(shí)現(xiàn)示例
這篇文章主要介紹了golang使用json格式實(shí)現(xiàn)增刪查改的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05Go?panic的三種產(chǎn)生方式細(xì)節(jié)探究
這篇文章主要介紹了Go?panic的三種產(chǎn)生方式細(xì)節(jié)探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12Golang的Crypto/SHA256庫(kù)實(shí)戰(zhàn)指南
無(wú)論是在保護(hù)數(shù)據(jù)安全、驗(yàn)證數(shù)據(jù)完整性,還是在構(gòu)建復(fù)雜的安全系統(tǒng)中,crypto/sha256都是Golang程序員不可或缺的工具,本文主要介紹了Golang的Crypto/SHA256庫(kù)實(shí)戰(zhàn)指南,感興趣的可以了解一下2024-02-02Golang中生成隨機(jī)字符串并復(fù)制到粘貼板的方法
這篇文章主要介紹了Golang中生成隨機(jī)字符串并復(fù)制到粘貼板的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12