-
Notifications
You must be signed in to change notification settings - Fork 0
/
lock.go
52 lines (44 loc) · 1.27 KB
/
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package redislock
import (
"context"
"errors"
"time"
"github.com/WeiJiadong/redislock/internal"
"github.com/go-redis/redis/v9"
)
// Mutex 互斥锁定义
type Mutex struct {
internal.LockInfo
}
// Lock 互斥锁加锁
func (l *Mutex) Lock(ctx context.Context, client *redis.Client) error {
ok, err := client.SetNX(ctx, l.Key, l.Val, l.Lease).Result()
if err != nil {
return err
}
if !ok {
return errors.New(internal.ErrLockFailed)
}
return nil
}
// Unlock 互斥锁解锁
func (l *Mutex) Unlock(ctx context.Context, client *redis.Client) error {
return internal.ExecLuaScript(ctx, client, l.Key, internal.UnLockScript, l.Val)
}
// Refresh 刷新互斥锁租约
func (l *Mutex) Refresh(ctx context.Context, client *redis.Client) error {
return internal.ExecLuaScript(ctx, client, l.Key, internal.RefreshScript, l.Val, l.Lease/time.Second)
}
// LockOrRefresh 互斥锁加锁或者刷新租约
func (l *Mutex) LockOrRefresh(ctx context.Context, client *redis.Client) error {
return internal.ExecLuaScript(ctx, client, l.Key, internal.LockOrRefreshScript, l.Val, l.Lease/time.Second)
}
// NewMutex 互斥锁构造函数
func NewMutex(Key, Val string, Lease time.Duration) *Mutex {
return &Mutex{
LockInfo: internal.LockInfo{
Key: Key,
Val: Val,
Lease: Lease,
}}
}