GoWindGoWind
首页
框架
GoWind Toolkit
  • 开源项目

    • GoWind Admin(后台管理)
    • GoWind CMS(内容管理)
    • GoWind UBA(行为分析)
    • GoWind Shop(电商)
    • GoWind Kanban(协作看板)
    • GoWind Ledger(家庭记账)
    • GoWind ShortPlay(短剧社区)
    • GoWind Ops(运维平台)
    • RushWind(Rust 生态)
  • Open Core(社区开源 · 企业版增强)

    • GoWind OA(协同办公)
    • GoWind ERP(业财一体)
    • GoWind WMS(多货主仓储)
  • 商业产品

    • GoWind IM(即时通讯)
    • GoWind CRM(B2B 销售管理)
    • GoWind Trade(外贸全流程管理)
    • GoWind IoT(物联网)
    • GoWind Edu(AI 教育)
    • GoWind MES(制造执行)
    • GoWind CDC(数据管道)
    • GoWind SDP(零信任网关)
    • GoWind Quant(量化研究)
    • GoWind Trade Radar(外贸选品雷达)
    • GoWind Game Radar(游戏立项雷达)
  • 简体中文
  • English
GitHub
首页
框架
GoWind Toolkit
  • 开源项目

    • GoWind Admin(后台管理)
    • GoWind CMS(内容管理)
    • GoWind UBA(行为分析)
    • GoWind Shop(电商)
    • GoWind Kanban(协作看板)
    • GoWind Ledger(家庭记账)
    • GoWind ShortPlay(短剧社区)
    • GoWind Ops(运维平台)
    • RushWind(Rust 生态)
  • Open Core(社区开源 · 企业版增强)

    • GoWind OA(协同办公)
    • GoWind ERP(业财一体)
    • GoWind WMS(多货主仓储)
  • 商业产品

    • GoWind IM(即时通讯)
    • GoWind CRM(B2B 销售管理)
    • GoWind Trade(外贸全流程管理)
    • GoWind IoT(物联网)
    • GoWind Edu(AI 教育)
    • GoWind MES(制造执行)
    • GoWind CDC(数据管道)
    • GoWind SDP(零信任网关)
    • GoWind Quant(量化研究)
    • GoWind Trade Radar(外贸选品雷达)
    • GoWind Game Radar(游戏立项雷达)
  • 简体中文
  • English
GitHub
  • 介绍

    • GoWind 框架
    • 框架整体架构
  • go-wind 核心

    • go-wind 核心框架
    • App 生命周期管理
    • Context 传播
    • Transport 抽象
    • Log 门面接口
  • go-wind-plugins 插件

    • go-wind-plugins 插件总览
    • 插件配置系统
    • 插件注册机制(SPI)
    • 日志适配插件
    • 传输协议插件
    • 消息中间件插件
    • 编码解码插件
    • 安全与认证插件
    • 链路追踪插件
    • 缓存插件
    • 对象存储插件(OSS)
    • 限流插件
    • 指标监控插件
    • AI 插件
    • 工作流插件
    • 数据库与缓存插件
    • Bootstrap 集成与网关插件
    • 压缩与序列化插件
    • 模板渲染与验证插件
  • go-wind-bootstrap 启动器

    • go-wind-bootstrap 声明式启动器
    • Bootstrap 配置系统
    • Bootstrap SPI 机制
    • 声明式中间件编排
    • Bootstrap 命令行集成
    • Bootstrap 实战示例
  • go-wind-flow 流程引擎

    • GoWind Flow 流程引擎
  • 教程

    • 快速入门教程
    • 自定义插件开发教程
    • 多协议同时监听教程
    • 框架迁移指南

限流插件

go-wind-plugins 提供统一的限流接口 ratelimit.Limiter,内置令牌桶、BBR、Sentinel 三种算法。

一、Limiter 接口

type Limiter interface {
    // Allow returns immediately. ok is false (with ErrLimited) if the
    // rate limit has been exceeded.
    Allow() (ok bool, err error)

    // Wait blocks until a request is permitted or ctx is cancelled.
    Wait(ctx context.Context) error

    Close() error
}

二、适配器列表

适配器导入路径算法
Token Bucketplugins/ratelimit/tokenbucket令牌桶算法
BBRplugins/ratelimit/bbrBBR 自适应限流
Sentinelplugins/ratelimit/sentinelalibaba/sentinel-golang

三、Token Bucket

import tbPlugin "github.com/tx7do/go-wind-plugins/ratelimit/tokenbucket"

// 令牌填充速率与突发容量
limiter, _ := tbPlugin.New(100, 50)
defer limiter.Close()

检查限流

allowed, err := limiter.Allow()
if !allowed {
    // 返回 429 Too Many Requests
}

等待通过

// 阻塞等待直到获取令牌或 ctx 取消
err := limiter.Wait(ctx)
if err != nil {
    // 超时
}

YAML 配置

ratelimit:
  tokenbucket:
    rate: 100
    burst: 50

四、BBR(自适应限流)

根据 CPU 负载与滑动窗口 QPS 自动调节,无需预设阈值:

import bbrPlugin "github.com/tx7do/go-wind-plugins/ratelimit/bbr"

limiter := bbrPlugin.New(
    bbrPlugin.WithCPUThreshold(80),          // CPU 阈值(%)
    bbrPlugin.WithWindow(10*time.Second),    // 统计窗口
    bbrPlugin.WithBucketCount(100),          // 窗口桶数
    bbrPlugin.WithMinQPS(800),               // 触发降级的最低 QPS
)
defer limiter.Close()

if ok, _ := limiter.Allow(); !ok {
    // 系统过载,拒绝请求
}

// 请求结束后回报耗时,供 BBR 统计
limiter.Done(rtt)

五、Sentinel

import sentinelPlugin "github.com/tx7do/go-wind-plugins/ratelimit/sentinel"

// 按资源创建限流器(底层为 alibaba/sentinel-golang)
limiter := sentinelPlugin.New("api.users",
    sentinelPlugin.WithTrafficType(base.Inbound),   // 流量类型
    sentinelPlugin.WithWaitInterval(100*time.Millisecond),
)
defer limiter.Close()

allowed, err := limiter.Allow()

// 需要手动管理 Entry 时(如取 BlockError 详情):
entry, blockErr := limiter.AllowEntry()
if entry != nil {
    defer limiter.ReleaseEntry(entry)
}

流控/熔断等规则通过 Sentinel 原生 API(sentinel.LoadRules)加载,插件聚焦资源级的 Limiter 封装。

YAML 配置

ratelimit:
  sentinel:
    flow_rules:
      - resource: "api.users"
        threshold: 100
        stat_interval_ms: 1000
        control_behavior: 0
      - resource: "api.orders"
        threshold: 50
        stat_interval_ms: 1000
    circuit_rules:
      - resource: "service.payment"
        strategy: 2              # 错误比例
        threshold: 0.5
        min_request_amount: 5
        time_window: 10

六、HTTP 中间件

HTTP/gRPC 传输层内置限流中间件(transport/http/middleware/ratelimit、transport/grpc/middleware/ratelimit):

import ratelimitMW "github.com/tx7do/go-wind-plugins/transport/http/middleware/ratelimit"

// 全局限流
router.Use(ratelimitMW.Middleware(limiter))

// 按 Key 限流:KeyFunc 提取维度,factory 按 Key 创建/复用 Limiter
router.Use(ratelimitMW.MiddlewareKeyed(
    func(r *http.Request) string { return r.RemoteAddr },  // 按 IP
    func(key string) ratelimit.Limiter { return newLimiterForKey(key) },
))

// 可选行为
ratelimitMW.WithWait()                                    // 排队等待而非立即拒绝
ratelimitMW.WithSkipFunc(func(r *http.Request) bool {     // 跳过健康检查
    return r.URL.Path == "/health"
})
ratelimitMW.WithErrorHandler(func(w http.ResponseWriter, r *http.Request, err error) {
    w.WriteHeader(http.StatusTooManyRequests)
})

相关文档

  • 插件配置系统
  • 安全与认证插件
  • 声明式中间件编排
Edit this page
最近更新:: 2026/11/3 12:42
Contributors: Bobo
Prev
对象存储插件(OSS)
Next
指标监控插件