輕量級限流工具 throttle

throttled 是一個非常輕量且易擴展的限流組件,我們可以將它輕鬆地集成到應用程序中,以實現限流和配額管理的能力。

簡介

throttled(https://github.com/throttled/throttled) 基於通用信元速率算法實現了對資源的訪問速率限制,資源可以是特定的 URL、用戶或者任何自定義的形式,可以很方便地與各種 http 和 rpc 框架進行集成。throttled 定義了限流元信息的存儲抽象,並內置了 memstore,redis store 等元信息存儲實現,我們可以根據具體的使用場景實現單機限流和集羣限流。

使用舉例

下面我們來基於 throttled 自帶的 http 限流組件實現一個簡單的 demo 試試看:

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/throttled/throttled/v2"
    "github.com/throttled/throttled/v2/store/memstore"
)

func main() {
    // 在 store 中添加 key 的數量限制
    store, err := memstore.New(65536)
    if err != nil {
        log.Fatal(err)
    }

    // 配置限流規則
    quota := throttled.RateQuota{
        MaxRate:  throttled.PerMin(20),
        MaxBurst: 5,
    }
    rateLimiter, err := throttled.NewGCRARateLimiter(store, quota)
    if err != nil {
        log.Fatal(err)
    }

    httpRateLimiter := throttled.HTTPRateLimiter{
        RateLimiter: rateLimiter,
        // 根據 path 進行限流
        VaryBy: &throttled.VaryBy{Path: true},
    }

    handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "hello, world\n")
    })
    http.ListenAndServe(":8080", httpRateLimiter.RateLimit(handler))
}

以上我們實現了一個按請求 path 進行限流的 http 服務,允許同一個 path 每分鐘 20 次請求,並支持短時間內最多 5 個請求的 burst。

此外,我們也可以通過指定 VaryBy 和 DeniedHandler 的方式對資源定義和超限處理進行一些更多的定製。

總結

throttled 是一款小巧輕量的限流組件,我們可以使用 throttled 非常輕鬆地實現單機或集羣的 QPS 限流能力。當然,throttled 的限流手段比較單一,當前僅支持基於 QPS 的限流規則,尚未擴展更全面的限流模式和更豐富的阻斷規則。

參考資料

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/PM4ocsopqlTezIheI4qZzA