This commit is contained in:
1 parent
624093773b
commit
568e516b1a
18 files changed
+912
-80
No files matched your search
@@ -0,0 +1,54 @@
|
||||
// Package ratelimit 维护可复用的原生限流执行器,不持有动态连接注册器。
|
||||
package ratelimit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
fault "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure"
|
||||
|
||||
"github.com/go-redis/redis_rate/v10"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// Redis 复用入口创建的 Redis 客户端执行 GCRA,不管理客户端生命周期。
|
||||
type Redis struct {
|
||||
limiter *redis_rate.Limiter `dc:"绑定既有客户端的原生分布式额度算法"`
|
||||
}
|
||||
|
||||
// NewRedis 创建分布式额度适配器。
|
||||
// 入参:client 为已完成启动探测的原生客户端。
|
||||
// 返回:没有可变包级状态的限流器。
|
||||
func NewRedis(client *redis.Client) *Redis { return &Redis{limiter: redis_rate.NewLimiter(client)} }
|
||||
|
||||
// AllowN 沿用既有额度、秒级周期及允许结果语义。
|
||||
// 入参:ctx 为取消上下文,cfg 为额度,count 为消耗令牌数。
|
||||
// 返回:是否允许;底层失败保留原始原因。
|
||||
func (r *Redis) AllowN(ctx context.Context, cfg *Config, count int) (bool, error) {
|
||||
var (
|
||||
result *redis_rate.Result
|
||||
err error
|
||||
)
|
||||
if cfg == nil {
|
||||
return false, fault.WrapContext(ctx, CodeRedisInput, "Redis rate limit input is required", errors.New("rate limit input is nil"))
|
||||
}
|
||||
if cfg.Total <= 0 || cfg.Rate <= 0 {
|
||||
return true, nil
|
||||
}
|
||||
result, err = r.limiter.AllowN(ctx, cfg.Key, redis_rate.Limit{Rate: cfg.Rate, Period: time.Duration(cfg.TimeInterval) * time.Second, Burst: cfg.Total}, count)
|
||||
if err != nil {
|
||||
return false, fault.WrapContext(ctx, CodeRedisAllow, "evaluate Redis rate limit failed", err)
|
||||
}
|
||||
return result.Allowed > 0, nil
|
||||
}
|
||||
|
||||
// Reset 清除当前主体的额度。
|
||||
// 入参:ctx 为取消上下文,cfg 为可信主体配置。
|
||||
// 返回:清理失败时保留错误链。
|
||||
func (r *Redis) Reset(ctx context.Context, cfg *Config) error {
|
||||
if cfg == nil {
|
||||
return fault.WrapContext(ctx, CodeRedisResetInput, "Redis rate limit reset input is required", errors.New("rate limit reset input is nil"))
|
||||
}
|
||||
return fault.WrapContext(ctx, CodeRedisReset, "reset Redis rate limit failed", r.limiter.Reset(ctx, cfg.Key))
|
||||
}
|
||||