Skip to content

Commit c9c6226

Browse files
Add function IsLockedTTLWithLimit checks if the key has been incremented more than the specified limit
1 parent 44080aa commit c9c6226

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

candiutils/locker.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,33 @@ func (r *RedisLocker) IsLockedTTL(key string, TTL time.Duration) bool {
104104
return incr > 1
105105
}
106106

107+
// IsLockedTTLWithLimit checks if the key has been incremented more than the specified limit
108+
// within the given TTL. If the key is being created for the first time, it sets the TTL.
109+
// Example usage: check if a key has been incremented more than 10 times within 1 minute.
110+
func (r *RedisLocker) IsLockedTTLWithLimit(key string, limit int, TTL time.Duration) bool {
111+
conn := r.pool.Get()
112+
defer conn.Close()
113+
114+
lockKey := fmt.Sprintf("%s:%s", r.lockeroptions.Prefix, key)
115+
incr, err := redis.Int64(conn.Do("INCR", lockKey))
116+
if err != nil {
117+
return false
118+
}
119+
120+
var expireTime time.Duration
121+
if TTL > 0 {
122+
expireTime = TTL
123+
} else {
124+
expireTime = r.lockeroptions.TTL
125+
}
126+
127+
if expireTime > 0 && incr == 1 {
128+
conn.Do("EXPIRE", lockKey, int(expireTime.Seconds()))
129+
}
130+
131+
return incr > int64(limit)
132+
}
133+
107134
func (r *RedisLocker) HasBeenLocked(key string) bool {
108135
conn := r.pool.Get()
109136
defer conn.Close()
@@ -234,3 +261,6 @@ func (NoopLocker) GetPrefixLocker() string { return "" }
234261

235262
// GetTTLLocker method
236263
func (NoopLocker) GetTTLLocker() time.Duration { return 0 }
264+
265+
// IsLockedTTLWithLimit method
266+
func (NoopLocker) IsLockedTTLWithLimit(string, int, time.Duration) bool { return false }

codebase/interfaces/locker.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ type (
1313
Lock(key string, timeout time.Duration) (unlockFunc func(), err error)
1414
GetPrefixLocker() string
1515
GetTTLLocker() time.Duration
16+
IsLockedTTLWithLimit(key string, limit int, TTL time.Duration) bool
1617
Closer
1718
}
1819
)

0 commit comments

Comments
 (0)