tokenbucket

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

Token Bucket Rate Limiter

该包实现了基于令牌桶算法的限流器。

特性

  • 支持设置桶的容量和填充速率

  • 支持限流等待和超时

  • 平滑限流,防止突发流量冲击

  • 简单易用

示例

bucket := tokenbucket.New(10, 100) // 容量10,速率100个/秒

for {
  bucket.Take() 
  // 使用令牌

  bucket.Put()
  // 返回令牌
}

接口

  • New 创建桶,传入容量和填充速率

  • Take 取走令牌,阻塞等待如果没有令牌

  • Put 返回令牌到桶中

  • Wait 阻塞等待一个令牌

  • Close 关闭桶

实现原理

  • 桶以固定速率填充令牌

  • 调用者取走令牌进行请求

  • 如果没有可用令牌,等待或阻塞请求

  • 滑动时间窗口周期性重置可用令牌数

优点

  • 控制访问速率,平滑限流

  • 容易配置限流速率

  • 支持限流等待

  • 无状态,可横向扩展

Documentation

Overview

Package tokenbucket implements a token bucket rate limiting algorithm.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type TokenBucket

type TokenBucket struct {
	// contains filtered or unexported fields
}

TokenBucket implements a token bucket that fills tokens at the specified rate. It allows limiting access to resources by rate.

func New

func New(rate float64, capacity int) *TokenBucket

New creates a new token bucket with the given rate and capacity.

func (*TokenBucket) Available

func (tb *TokenBucket) Available() int

Available returns the number of available tokens.

func (*TokenBucket) Capacity

func (tb *TokenBucket) Capacity() int

Capacity returns the capacity of the bucket.

func (*TokenBucket) Close

func (tb *TokenBucket) Close()

Close stops the filling goroutine and closes channels.

func (*TokenBucket) Put

func (tb *TokenBucket) Put() error

Put returns a token back to the bucket.

func (*TokenBucket) Rate

func (tb *TokenBucket) Rate() float64

Rate returns the fill rate of the bucket.

func (*TokenBucket) Take

func (tb *TokenBucket) Take() error

Take retrieves a token from the bucket. It blocks if no tokens available.

func (*TokenBucket) Wait

func (tb *TokenBucket) Wait()

Wait blocks until a token becomes available.

Jump to

Keyboard shortcuts

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