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 {
104
104
return incr > 1
105
105
}
106
106
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
+
107
134
func (r * RedisLocker ) HasBeenLocked (key string ) bool {
108
135
conn := r .pool .Get ()
109
136
defer conn .Close ()
@@ -234,3 +261,6 @@ func (NoopLocker) GetPrefixLocker() string { return "" }
234
261
235
262
// GetTTLLocker method
236
263
func (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 13
13
Lock (key string , timeout time.Duration ) (unlockFunc func (), err error )
14
14
GetPrefixLocker () string
15
15
GetTTLLocker () time.Duration
16
+ IsLockedTTLWithLimit (key string , limit int , TTL time.Duration ) bool
16
17
Closer
17
18
}
18
19
)
You can’t perform that action at this time.
0 commit comments