Skip to content

Commit b970fb8

Browse files
WanMuhafidzFaldiagungdwiprasetyo
authored andcommitted
Locker: add option function locker with time to live, for handling if service down and key still exist
1 parent f011bb5 commit b970fb8

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

candiutils/locker.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,13 @@ func NewRedisLocker(pool *redis.Pool) *RedisLocker {
2525
return &RedisLocker{pool: pool}
2626
}
2727

28-
func (r *RedisLocker) IsLocked(key string) bool {
28+
func (r *RedisLocker) IsLocked(key string, expiration ...time.Duration) bool {
2929
conn := r.pool.Get()
3030
incr, _ := redis.Int64(conn.Do("INCR", key))
31+
32+
if len(expiration) > 0 {
33+
conn.Do("EXPIRE", key, int(expiration[0].Seconds()))
34+
}
3135
conn.Close()
3236

3337
return incr > 1
@@ -122,6 +126,9 @@ func (r *RedisLocker) Lock(key string, timeout time.Duration) (unlockFunc func()
122126
// IsLocked method
123127
func (NoopLocker) IsLocked(string) bool { return false }
124128

129+
// IsLocked method
130+
func (NoopLocker) IsLockedWithTTL(string, time.Duration) bool { return false }
131+
125132
// HasBeenLocked method
126133
func (NoopLocker) HasBeenLocked(string) bool { return false }
127134

codebase/interfaces/locker.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ type (
66
// Locker abstraction, lock concurrent process
77
Locker interface {
88
IsLocked(key string) bool
9+
IsLockedWithTTL(key string, timeout time.Duration) bool
910
HasBeenLocked(key string) bool
1011
Unlock(key string)
1112
Reset(key string)

0 commit comments

Comments
 (0)