您现在的位置是:网站首页> 编程资料编程资料
Go如何实现HTTP请求限流示例_Golang_
2023-05-26
408人已围观
简介 Go如何实现HTTP请求限流示例_Golang_
在开发高并发系统时有三把利器用来保护系统:缓存、降级和限流!为了保证在业务高峰期,线上系统也能保证一定的弹性和稳定性,最有效的方案就是进行服务降级了,而限流就是降级系统最常采用的方案之一。
这里为大家推荐一个开源库 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(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) rese
相关内容
- golang中for循环遍历channel时需要注意的问题详解_Golang_
- 如何编写Go语言中间件的实例教程_Golang_
- golang中定时器cpu使用率高的现象详析_Golang_
- 浅谈go-restful框架的使用和实现_Golang_
- Golang信号处理及如何实现进程的优雅退出详解_Golang_
- golang的httpserver优雅重启方法详解_Golang_
- golang中struct和interface的基础使用教程_Golang_
- 利用GO语言实现多人聊天室实例教程_Golang_
- 深入Golang之context的用法详解_Golang_
- GoLang 中的随机数的示例代码_Golang_
点击排行
本栏推荐
