window

package
v0.0.0-...-2824e21 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 8, 2023 License: MIT Imports: 4 Imported by: 0

README

Sliding Window Rate Limiter

该包实现了基于滑动窗口的限流算法。

特性

  • 将时间窗口分多个桶,根据桶内计数限流

  • 滑动窗口,重置统计

  • 支持设置窗口和桶的时间大小

  • 获取任意时间范围内的请求数

  • 简单易用

示例

sw := window.New(10*time.Second, 1*time.Second, 10) 

if !sw.Allow() {
  // 限流逻辑
}

count := sw.Count(5*time.Second) // 最近5秒请求数

接口

  • New 创建滑动窗口,传入窗口大小,桶大小和桶数

  • Allow 处理请求,检查是否限流

  • Count 获取时间范围内请求数

  • Reset 重置所有桶的计数

实现原理

  • 将时间窗口均分为多个桶

  • 每个桶记录一段时间内的请求数

  • 滑动窗口,旧桶重置计数

  • 汇总多个桶的计数得出时间范围内请求数

优点

  • 精确限流时间范围内请求率

  • 记录少量数据,内存占用低

  • 滑动窗口,限流平滑自然

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type SlidingWindow

type SlidingWindow struct {
	sync.Mutex
	// contains filtered or unexported fields
}

SlidingWindow implements a fixed-size sliding window for rate limiting.

func New

func New(windowSize, bucketSize time.Duration, bucketCount int) (*SlidingWindow, error)

NewSlidingWindow creates a new sliding window with the given window size, bucket size and bucket count. Window size must be divisible by bucket size.

func (*SlidingWindow) Allow

func (sw *SlidingWindow) Allow() bool

Allow reports whether a new event should be allowed, and if so increments the

func (*SlidingWindow) BucketCount

func (sw *SlidingWindow) BucketCount(idx int) int

BucketCount returns the current count for the given bucket index.

func (*SlidingWindow) Count

func (sw *SlidingWindow) Count(d time.Duration) int

Count returns the total count for the given duration

func (*SlidingWindow) Reset

func (sw *SlidingWindow) Reset()

Reset resets the counts in all buckets to 0.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL