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