-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlocker.go
53 lines (44 loc) · 1.26 KB
/
locker.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
53
package lock
import (
"time"
)
type Locker interface {
Acquire(key string, opts ...LockerOpt) (Lock, error)
}
type Lock interface {
Release() error
}
func DefaultOptions() *Options {
return &Options{
AcquireTimeout: 5 * time.Second,
Try: false,
TTL: 0,
}
}
type Options struct {
// 获取锁超时时间, 超过此时间没有获取到锁返回 ErrDeadlineExceeded 错误
AcquireTimeout time.Duration
// 锁过期时间,如果为0则不会过期,需要手动释放锁
TTL time.Duration
// 尝试获取锁,如果没有获取到返回 ErrAlreadyLocked 错误
Try bool
}
type LockerOpt func(op *Options)
// WithTry 非堵塞尝试获取锁,如果没有获取到返回 ErrAlreadyLocked 错误
func WithTry(try bool) LockerOpt {
return LockerOpt(func(op *Options) {
op.Try = try
})
}
// WithAcquireTimeout 获取锁超时时间, 超过此时间没有获取到锁返回 ErrDeadlineExceeded 错误
func WithAcquireTimeout(timeout time.Duration) LockerOpt {
return LockerOpt(func(op *Options) {
op.AcquireTimeout = timeout
})
}
// WithLockTTL 锁过期时间,如果为0则会自动续约不会过期,需要手动释放锁
func WithLockTTL(ttl time.Duration) LockerOpt {
return LockerOpt(func(op *Options) {
op.TTL = ttl
})
}