File tree Expand file tree Collapse file tree 2 files changed +31
-0
lines changed Expand file tree Collapse file tree 2 files changed +31
-0
lines changed Original file line number Diff line number Diff 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+
107134func (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
236263func (NoopLocker ) GetTTLLocker () time.Duration { return 0 }
264+
265+ // IsLockedTTLWithLimit method
266+ func (NoopLocker ) IsLockedTTLWithLimit (string , int , time.Duration ) bool { return false }
Original file line number Diff line number Diff line change 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)
You can’t perform that action at this time.
0 commit comments