传入的total和rate任意一个小于等于0,认为不限速

This commit is contained in:
白茶清欢 2023-03-09 12:17:54 +08:00
parent c318733af7
commit 2018e816c7
1 changed files with 15 additions and 3 deletions

View File

@ -34,12 +34,15 @@ func InitLimiter(redisClient *redisInstance.Client) {
// Author : go_developer@163.com<白茶清欢>
//
// 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)
if nil != err {
return false
return false, err
}
return res.Allowed > 0
return res.Allowed > 0, nil
}
// Minute 每分钟允许访问数
@ -48,6 +51,9 @@ func Second(ctx context.Context, key string, total, rate int) bool {
//
// Date : 11:46 2023/3/9
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)
if nil != 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
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)
if nil != 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
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{
Rate: rate,
Period: 24 * time.Hour,