支持基于redis的流量控制 #1
@ -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,
|
||||||
|
Loading…
Reference in New Issue
Block a user