跳到主要内容
版本: websocket_v1.x.x

LoadShed

Release Discord Test

Fiber 的 LoadShed 中间件旨在通过根据特定负载标准削减请求来帮助管理服务器负载。

注意:需要 Go 1.19 及以上版本

安装

此中间件支持 Fiber v2

go get -u github.com/gofiber/fiber/v2
go get -u github.com/gofiber/contrib/loadshed

签名

loadshed.New(config ...loadshed.Config) fiber.Handler

示例

要在 Fiber 应用程序中使用 LoadShed 中间件,请导入它并将其应用于您的 Fiber 应用。这里有一个示例

package main

import (
"github.com/gofiber/fiber/v2"
loadshed "github.com/gofiber/contrib/loadshed"
)

func main() {
app := fiber.New()

// Configure and use LoadShed middleware
app.Use(loadshed.New(loadshed.Config{
Criteria: &loadshed.CPULoadCriteria{
LowerThreshold: 0.75, // Set your own lower threshold
UpperThreshold: 0.90, // Set your own upper threshold
Interval: 10 * time.Second,
Getter: &loadshed.DefaultCPUPercentGetter{},
},
}))

app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Welcome!")
})

app.Listen(":3000")
}

配置

Fiber 中的 LoadShed 中间件提供了各种配置选项,可根据您的应用程序需求定制负载削减行为。

属性类型描述默认
下一个func(*fiber.Ctx) bool当返回 true 时跳过此中间件的函数。nil
标准LoadCriteria用于定义负载削减标准的接口。&CPULoadCriteria{...}

LoadCriteria

LoadCriteria 是 LoadShed 中间件中的一个接口,它定义了确定何时削减系统负载的标准。该接口的不同实现可以使用各种指标和算法来决定何时以及如何削减传入请求,以维护系统性能。

CPULoadCriteria

CPULoadCriteriaLoadCriteria 接口的一个实现,使用 CPU 负载作为衡量指标来决定是否削减请求。

属性

属性类型描述
LowerThresholdfloat64CPU 使用率下限阈值,表示为一个小数 (0.0 到 1.0)。当 CPU 使用率超过此阈值时,会考虑削减请求。
UpperThresholdfloat64CPU 使用率上限阈值,表示为一个小数 (0.0 到 1.0)。当 CPU 使用率超过此阈值时,所有请求都会被削减。
Intervaltime.Duration用于计算 CPU 使用率平均值的时隔。
GetterCPUPercentGetter用于获取 CPU 使用率百分比的接口。

工作原理

CPULoadCriteria 根据 CPU 使用率确定系统负载,并决定是否削减传入请求。其工作原理如下:

  • CPU 使用率测量:它测量指定时间间隔内的 CPU 使用率。
  • 阈值:利用 LowerThresholdUpperThreshold 值来决定何时开始削减请求。
  • 按比例的拒绝概率:
    • 低于 LowerThreshold:不拒绝任何请求,因为系统负载处于可接受范围内。
    • 介于 LowerThresholdUpperThreshold 之间:拒绝请求的概率随着 CPU 使用率接近 UpperThreshold 而增加。这使用以下公式计算:
      rejectionProbability := (cpuUsage - LowerThreshold*100) / (UpperThreshold - LowerThreshold)
    • 高于 UpperThreshold:所有请求都会被拒绝,以防止系统过载。

这种机制确保系统可以自适应地管理其负载,在不同的流量条件下保持稳定性和性能。

默认配置

这是 LoadShed 中间件中 LoadCriteria 的默认配置。

var ConfigDefault = Config{
Next: nil,
Criteria: &CPULoadCriteria{
LowerThreshold: 0.90, // 90% CPU usage as the start point for considering shedding
UpperThreshold: 0.95, // 95% CPU usage as the point where all requests are shed
Interval: 10 * time.Second, // CPU usage is averaged over 10 seconds
Getter: &DefaultCPUPercentGetter{}, // Default method for getting CPU usage
},
}