ratelimit

package
v0.0.0-...-52c6137 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2021 License: MIT Imports: 9 Imported by: 0

README

限流

限流分为单机限流和分布式限流。

单机限流一般分为 令牌桶算法和漏斗算法限流。

限流算法

令牌桶算法限流

代码实现:golang.org/x/time/rate

漏斗算法限流

代码实现:https://github.com/uber-go/ratelimit

滑动窗口

自适应限流

但是采用漏斗桶/令牌桶的缺点是太被动, 不能快速适应流量变化。
因此我们需要一种自适应的限流算法,即: 过载保护,根据系统当前的负载自动丢弃流量。

可以参考 BBR算法实现: https://github.com/go-kratos/kratos/blob/master/pkg/ratelimit/bbr/bbr.go

扩展

###Sentinel-golang 版本

sentinel 官网:https://sentinelguard.io/zh-cn/index.html

sentinel 是面向分布式服务架构的高可用流量控制组件

Github

https://github.com/alibaba/sentinel-golang

特性

Sentinel Go 1.0 版本对齐了 Java 版本核心的高可用防护和容错能力,包括

  • 限流
  • 流量整形
  • 并发控制
  • 熔断降级
  • 系统自适应保护
  • 热点防护

等特性

更多使用介绍看这里:流控降级组件 Sentinel Go简介

Reference

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewCounter

func NewCounter(rate int, cycle time.Duration) *counter

NewCounter @Description: 单机版计数器 构造函数 @param rate @param cycle @return *counter

func NewLeakyBucket

func NewLeakyBucket(rate int) *leakyBucket

func NewSlidingWindow

func NewSlidingWindow(max int, slotDuration time.Duration, winDuration time.Duration) *slidingWindow

Types

type RedisTokenBucket

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

A RedisTokenBucket controls how frequently events are allowed to happen with in one second.

func NewTokenLimiter

func NewTokenLimiter(rate, burst int, store *redis.Client, key string) *RedisTokenBucket

NewTokenLimiter returns a new TokenLimiter that allows events up to rate and permits bursts of at most burst tokens.

func (*RedisTokenBucket) Allow

func (lim *RedisTokenBucket) Allow() bool

Allow is shorthand for AllowN(time.Now(), 1).

func (*RedisTokenBucket) AllowN

func (lim *RedisTokenBucket) AllowN(now time.Time, n int) bool

AllowN reports whether n events may happen at time now. Use this method if you intend to drop / skip events that exceed the rate rate. Otherwise use Reserve or Wait.

type TokenBucket

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

TokenBucket 单机版令牌桶

func NewTokenBucket

func NewTokenBucket(maxBucket int, sec time.Duration) *TokenBucket

func (*TokenBucket) Allow

func (t *TokenBucket) Allow() bool

Jump to

Keyboard shortcuts

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