支持基于redis的流量控制 #1

Merged
zhangdeman merged 2 commits from feature/rate_limit into master 2023-03-09 14:06:43 +08:00
Showing only changes of commit 2018e816c7 - Show all commits

View File

@ -34,12 +34,15 @@ func InitLimiter(redisClient *redisInstance.Client) {
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 11:42 2023/3/9 // Date : 11:42 2023/3/9
func Second(ctx context.Context, key string, total, rate int) bool { func Second(ctx context.Context, key string, total, rate int) (bool, error) {
if total <= 0 || rate <= 0 {
return true, nil
}
res, err := limiter.AllowN(ctx, key, redis_rate.PerSecond(total), rate) res, err := limiter.AllowN(ctx, key, redis_rate.PerSecond(total), rate)
if nil != err { if nil != err {
return false return false, err
} }
return res.Allowed > 0 return res.Allowed > 0, nil
} }
// Minute 每分钟允许访问数 // Minute 每分钟允许访问数
@ -48,6 +51,9 @@ func Second(ctx context.Context, key string, total, rate int) bool {
// //
// Date : 11:46 2023/3/9 // Date : 11:46 2023/3/9
func Minute(ctx context.Context, key string, total, rate int) (bool, error) { func Minute(ctx context.Context, key string, total, rate int) (bool, error) {
if total <= 0 || rate <= 0 {
return true, nil
}
res, err := limiter.AllowN(ctx, key, redis_rate.PerMinute(total), rate) res, err := limiter.AllowN(ctx, key, redis_rate.PerMinute(total), rate)
if nil != err { if nil != err {
return false, err return false, err
@ -61,6 +67,9 @@ func Minute(ctx context.Context, key string, total, rate int) (bool, error) {
// //
// Date : 11:47 2023/3/9 // Date : 11:47 2023/3/9
func Hour(ctx context.Context, key string, total, rate int) (bool, error) { func Hour(ctx context.Context, key string, total, rate int) (bool, error) {
if total <= 0 || rate <= 0 {
return true, nil
}
res, err := limiter.AllowN(ctx, key, redis_rate.PerHour(total), rate) res, err := limiter.AllowN(ctx, key, redis_rate.PerHour(total), rate)
if nil != err { if nil != err {
return false, err return false, err
@ -74,6 +83,9 @@ func Hour(ctx context.Context, key string, total, rate int) (bool, error) {
// //
// Date : 11:47 2023/3/9 // Date : 11:47 2023/3/9
func Day(ctx context.Context, key string, total, rate int) (bool, error) { func Day(ctx context.Context, key string, total, rate int) (bool, error) {
if total <= 0 || rate <= 0 {
return true, nil
}
res, err := limiter.AllowN(ctx, key, redis_rate.Limit{ res, err := limiter.AllowN(ctx, key, redis_rate.Limit{
Rate: rate, Rate: rate,
Period: 24 * time.Hour, Period: 24 * time.Hour,