Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add function IsLockedTTLWithLimit checks if the key has been incremen… #53

Open
wants to merge 1 commit into
base: development
Choose a base branch
from

Conversation

WanMuhafidzFaldi
Copy link
Contributor

IsLockedTTLWithLimit checks if the key has been incremented more than the specified limit
within the given TTL. If the key is being created for the first time, it sets the TTL.
Example usage: check if a key has been incremented more than 10 times within 1 minute.

@WanMuhafidzFaldi WanMuhafidzFaldi requested a review from a team as a code owner November 15, 2024 04:09
@WanMuhafidzFaldi WanMuhafidzFaldi requested review from isogram, fathiraz and agungdwiprasetyo and removed request for a team November 15, 2024 04:09
// IsLockedTTLWithLimit checks if the key has been incremented more than the specified limit
// within the given TTL. If the key is being created for the first time, it sets the TTL.
// Example usage: check if a key has been incremented more than 10 times within 1 minute.
func (r *RedisLocker) IsLockedTTLWithLimit(key string, limit int, TTL time.Duration) bool {
Copy link
Member

@agungdwiprasetyo agungdwiprasetyo Nov 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

imo, better create general method IsLockedWithOption instead add new specific method for new feature.
enhance LockerOptions add new field Limit and set default value to 1 in constructor.

example:

Suggested change
func (r *RedisLocker) IsLockedTTLWithLimit(key string, limit int, TTL time.Duration) bool {
func (r *RedisLocker) IsLockedWithOption(key string, opts ...LockerOption) bool {
conn := r.pool.Get()
defer conn.Close()
lockOpt := r.lockeroptions
for _, opt := range opts {
opt(&lockOpt)
}
lockKey := fmt.Sprintf("%s:%s", r.lockeroptions.Prefix, key)
incr, err := redis.Int64(conn.Do("INCR", lockKey))
if err != nil {
return false
}
withLimit := lockOpt.Limit > 1
if lockOpt.TTL > 0 && !(withLimit && incr == 1) {
conn.Do("EXPIRE", lockKey, int(lockOpt.TTL.Seconds()))
}
return incr > int64(lockOpt.Limit)
}

also applies to IsLockedTTL method

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants