From d1433040df77f9f9becb1097226897c65fc57948 Mon Sep 17 00:00:00 2001 From: jiangyong Date: Fri, 8 May 2026 18:33:50 +0800 Subject: [PATCH] option --- limit.go | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/limit.go b/limit.go index 8432029..6fe2906 100644 --- a/limit.go +++ b/limit.go @@ -9,11 +9,11 @@ import ( ) type WindowsLimitOption struct { - keyPrefix string //redis可以前缀,会拼接上succ和fail - limitCount int64 //限制数量 - scope time.Duration //限制时间区间,默认一分钟 - succKey string - failKey string + Key string //redis可以前缀,会拼接上succ和fail + Count int64 //限制数量 + Size time.Duration //限制时间区间,默认一分钟 + succKey string + failKey string } type WindowsLimit struct { client *redis.Client @@ -22,9 +22,9 @@ type WindowsLimit struct { func NewWindowsLimitOption() *WindowsLimitOption { return &WindowsLimitOption{ - keyPrefix: fmt.Sprintf("windows:limit:%s:%d", time.Now().Format("20060102"), time.Now().UnixMilli()), - limitCount: 1000, - scope: time.Second * 60, + Key: fmt.Sprintf("windows:limit:%s:%d", time.Now().Format("20060102"), time.Now().UnixMilli()), + Count: 1000, + Size: time.Second * 60, } } @@ -37,7 +37,7 @@ func NewWindowsLimit(client *redis.Client, option *WindowsLimitOption) *WindowsL func (w *WindowsLimit) tidy() { now := time.Now().UnixMilli() - start := now - w.option.scope.Milliseconds() + start := now - w.option.Size.Milliseconds() pipe := w.client.Pipeline() pipe.ZRemRangeByScore(w.option.failKey, "0", fmt.Sprintf("%d", start)) @@ -47,7 +47,7 @@ func (w *WindowsLimit) tidy() { func (w *WindowsLimit) Count() (int64, int64, error) { now := time.Now().UnixMilli() - start := now - w.option.scope.Milliseconds() + start := now - w.option.Size.Milliseconds() pipe := w.client.Pipeline() succCmd := pipe.ZCount(w.option.succKey, fmt.Sprintf("%d", start), fmt.Sprintf("%d", now)) @@ -61,7 +61,7 @@ func (w *WindowsLimit) Count() (int64, int64, error) { func (w *WindowsLimit) Allow() bool { now := time.Now().UnixMilli() - start := now - w.option.scope.Milliseconds() + start := now - w.option.Size.Milliseconds() pipe := w.client.Pipeline() succCmd := w.client.ZCount(w.option.succKey, fmt.Sprintf("%d", start), fmt.Sprintf("%d", now)) _, err := pipe.Exec() @@ -69,7 +69,7 @@ func (w *WindowsLimit) Allow() bool { return false } - if succCmd.Val() >= w.option.limitCount { + if succCmd.Val() >= w.option.Count { return false } return true @@ -85,8 +85,8 @@ func (w *WindowsLimit) Add(succ bool) error { pipe.ZAdd(w.option.failKey, redis.Z{Score: float64(now), Member: fmt.Sprintf("%d:%d", now, rand.Int())}) } - pipe.Expire(w.option.failKey, w.option.scope) - pipe.Expire(w.option.succKey, w.option.scope) + pipe.Expire(w.option.failKey, w.option.Size) + pipe.Expire(w.option.succKey, w.option.Size) _, err := pipe.Exec() return err }