sentinel

package
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2023 License: MIT Imports: 6 Imported by: 0

README

全局流控

背景介绍

有N个相同的pod,运行服务A;服务A会调用一个接口B,这个接口只允许我们50 QPS。

这种情况下,无论这服务A(运行了100份)怎么调度、运行,调用接口B的频率控制不能超过50 QPS。

如果超过了50 QPS,如果有个等待队列也挺好,等待最大超时时间(可自定义,假设设置2s),如果请求等待超过2s,则直接返回等待超时。

每个服务如果有对外接口的调用,那么会集成这个分布式全局流控组件,用于控制对外部接口的调用频率

任务目标:

  • 基于Redis实现支持分布式的流控;
  • 使用令牌桶实现;
  • 实现等待(重试)功能;
  • 使用lua脚本避免Redis操作可能会出现的并发问题
  • 可自定义配置流控的阈值
  • ……

在使用时需要在main函数里load的要配置的服务的规则,传入的是一个服务名称推荐使用调用API的接口名称:

  • http接口可以使用"/api/v1/login"这种
  • Grpc推荐使用"messageservicepb.MessageService/SendSMS"
……
rdb := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", 
		DB:       0,  
	})
	rules := []*Rule{}
	resource := "/api/v1/login"
	rules = append(rules, &Rule{
		Resource:     resource,
		Threshold:    5, 
		ForcedUpdate: false,
	})
	if err := LoadRules(context.Background(), rdb, rules); err != nil {
		t.Error(err)
		return
	}
……

Allow方法的使用

Rule已经被设置过
……
resource := "/api/v1/login"
if err := Allow(context.Background(), resource) ; err != nil {
  // 获取令牌失败,当前流控以达到阈值上限
}

……

Wait方法的使用

Rule已经被设置过
……
resource := "/api/v1/login"
// Wait可传入retry参数,在获取令牌失败后,进行重试,间隔是1秒
if err := Wait(context.Background(), resource,3) ; err != nil {
  // 获取令牌失败,且已经自动尝试3次均未获取到令牌,当前流控以达到阈值上限
}

……

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (

	// 1011010001,
	ErrAcquireFailed = errors.New("Number of requests exceeds threshold")
)
View Source
var (
	SentinelRedisKey = "sentinel:configs"
)

Functions

func Allow

func Allow(ctx context.Context, resource string) error

Allow 尝试获取令牌

func IsValidRule

func IsValidRule(rule *Rule) error

IsValidRule 检查参数

func LoadRules

func LoadRules(ctx context.Context, rdb *redis.Client, rules []*Rule) error

LoadRules 加载规则

func Wait

func Wait(ctx context.Context, resource string, retry int) error

Wait 如果失败会延时尝试请求 retry 重试次数,如果出现失败,则会根据传入的retry数值进行重试,通常是200毫秒重试一次

Types

type Rule

type Rule struct {
	// 资源表示资源名称。
	Resource string `json:"resource"`
	// Threshold  阈值   表示QPS
	Threshold int64 `json:"threshold"`
	// 是否强制更新,true会强制更新参数
	ForcedUpdate bool `json:"forced_update"`
}

type TokenBucketLimiter

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

TokenBucketLimiter 令牌桶限流器

Jump to

Keyboard shortcuts

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