limiterhelper

package
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2022 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package limiterhelper 限制器帮助模块,用于快速构造限制器 限制器可以用于防止短时间内大量请求同时处理,比如缓存防击穿,防爬虫等

Index

Constants

This section is empty.

Variables

View Source
var Defaultopt = Options{
	MaxSize:     100,
	WarningSize: 80,
}

Defaultopt 默认的可选配置

View Source
var ErrAlreadyHasHook = errors.New("already has hook")

ErrAlreadyHasHook limiter的指定钩子已经设置过了

View Source
var ErrLimiterMaxSizeMustLargerThanWaringSize = errors.New("limiter's maxsize must larger than waring size")

ErrLimiterMaxSizeMustLargerThanWaringSize limiter的最大容量必须大于警戒容量

Functions

func WithMaxSize

func WithMaxSize(maxsize int64) optparams.Option[Options]

WithMaxSize 设置最大水位,必须大于0

func WithWarningSize

func WithWarningSize(warningSize int64) optparams.Option[Options]

WithWarningSize 设置警戒水位,必须大于0

Types

type Hook

type Hook func(res, maxsize int64) error

钩子函数 @params res int64 当前水位 @params maxsize int64 最大水位

type LimiterABC

type LimiterABC struct {
	WarningHook Hook
	FullHook    Hook
	Hookslock   sync.RWMutex
	Opt         Options
}

LimiterABC 分布式限制器公用组件

func New

func New(opts ...optparams.Option[Options]) (*LimiterABC, error)

func (*LimiterABC) Capacity

func (l *LimiterABC) Capacity() int64

Capacity 限制器最大容量

func (*LimiterABC) CheckWaterline

func (l *LimiterABC) CheckWaterline(size int64, blocked bool) bool

CheckWaterline 检查水位是否已满 @params size int64 当前水位 @returns bool 是否水位已满

func (*LimiterABC) OnFull

func (c *LimiterABC) OnFull(fn Hook) error

OnFull 注册在到水位漫时的钩子 @params fn Hook 钩子函数

func (*LimiterABC) OnWarning

func (c *LimiterABC) OnWarning(fn Hook) error

OnWarning 注册在到警戒水位时的钩子 @params fn Hook 钩子函数

type LimiterInterface

type LimiterInterface interface {
	//注水,返回值true表示注水成功,false表示满了无法注水,抛出异常返回true
	Flood(context.Context, int64) (bool, error)
	//水位
	WaterLevel(context.Context) (int64, error)
	//容量
	Capacity() int64
	//是否容量已满
	IsFull(context.Context) (bool, error)
	//重置
	Reset(context.Context) error
	//注册到警戒水位的钩子,钩子会在执行Flood方法时触发
	OnWarning(fn Hook) error
	//注册水位满时的钩子,钩子会在执行Flood方法时触发
	OnFull(fn Hook) error
}

LimiterInterface 限制器接口

type Options

type Options struct {
	MaxSize     int64
	WarningSize int64
}

Options broker的配置

Jump to

Keyboard shortcuts

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