-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathlock.go
More file actions
89 lines (71 loc) · 1.61 KB
/
lock.go
File metadata and controls
89 lines (71 loc) · 1.61 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package trylock
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/labring/aiproxy/core/common"
"github.com/redis/go-redis/v9"
log "github.com/sirupsen/logrus"
)
var memRecord = sync.Map{}
func init() {
go cleanMemLock()
}
func cleanMemLock() {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for now := range ticker.C {
memRecord.Range(func(key, value any) bool {
exp, ok := value.(time.Time)
if !ok {
panic(fmt.Sprintf("mem lock type mismatch: %T", value))
}
if now.After(exp) {
memRecord.CompareAndDelete(key, value)
}
return true
})
}
}
func MemLock(key string, expiration time.Duration) bool {
now := time.Now()
newExpiration := now.Add(expiration)
for {
actual, loaded := memRecord.LoadOrStore(key, newExpiration)
if !loaded {
return true
}
oldExpiration, ok := actual.(time.Time)
if !ok {
panic(fmt.Sprintf("mem lock type mismatch: %T", actual))
}
if now.After(oldExpiration) {
if memRecord.CompareAndSwap(key, actual, newExpiration) {
return true
}
continue
}
return false
}
}
func Lock(key string, expiration time.Duration) bool {
if !common.RedisEnabled {
return MemLock(key, expiration)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_, err := common.RDB.SetArgs(ctx, common.RedisKey(key), true, redis.SetArgs{Mode: "NX", TTL: expiration}).
Result()
if errors.Is(err, redis.Nil) {
return false
}
if err != nil {
if MemLock("lockerror", 5*time.Second) {
log.Errorf("try notify error: %v", err)
}
return MemLock(key, expiration)
}
return true
}