/
lock.go
37 lines (30 loc) · 910 Bytes
/
lock.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package lock
import (
"context"
"github.com/go-redis/redis"
"time"
)
type RedisLock struct {
conn *redis.Client
timeout time.Duration
key string
val string
}
func NewRedisLock(conn *redis.Client, key, val string, timeout time.Duration) *RedisLock {
return &RedisLock{conn: conn, timeout: timeout, key: key, val: val}
}
//return true ===> Get the lock successfully
func (lock *RedisLock) TryLock() error {
return lock.conn.SetNX(context.Background(), lock.key, lock.val, lock.timeout).Err()
}
func (lock *RedisLock) UnLock() error {
luaDel := redis.NewScript("if redis.call('get',KEYS[1]) == ARGV[1] then " +
"return redis.call('del',KEYS[1]) else return 0 end")
return luaDel.Run(context.Background(), lock.conn, []string{lock.key}, lock.val).Err()
}
func (lock *RedisLock) GetLockKey() string {
return lock.key
}
func (lock *RedisLock) GetLockVal() string {
return lock.val
}