-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathredisson_test.go
More file actions
103 lines (90 loc) · 2.05 KB
/
redisson_test.go
File metadata and controls
103 lines (90 loc) · 2.05 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package redisson_test
import (
"context"
"sync"
"testing"
"time"
"github.com/go-redis/redis/v8"
"github.com/troyhantech/redisson"
"github.com/troyhantech/redisson/mutex"
)
func TestMutex(t *testing.T) {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
DB: 0,
})
redissonClient := redisson.New(context.Background(), client)
options := []mutex.Option{
mutex.WithExpireDuration(30000 * time.Millisecond),
}
mutex1 := redissonClient.NewMutex("redisson_mutex", options...)
err := mutex1.Lock(context.Background())
if err != nil {
t.Error(err)
return
}
t.Log("lock successfully")
// 测试:其他协程无法解锁
waitGroup := sync.WaitGroup{}
waitGroup.Add(1)
go func() {
defer func() {
waitGroup.Done()
}()
var mutex2 = redissonClient.NewMutex("redisson_mutex")
err = mutex2.Unlock(context.Background())
if err != nil {
t.Error(err)
return
}
t.Log("unlock successfully")
}()
waitGroup.Wait()
// 测试:加锁的协程可以顺利解锁
err = mutex1.Unlock(context.Background())
if err != nil {
t.Error(err)
return
}
t.Log("unlock successfully")
}
func TestRWMutex(t *testing.T) {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
DB: 0,
})
redissonClient := redisson.New(context.Background(), client)
options := []mutex.Option{
mutex.WithExpireDuration(30 * time.Millisecond),
}
mutex1 := redissonClient.NewRWMutex("redisson_mutex", options...)
err := mutex1.Lock(context.Background())
if err != nil {
t.Error(err)
return
}
t.Log("lock successfully")
// 测试:其他协程无法解锁
waitGroup := sync.WaitGroup{}
waitGroup.Add(1)
go func() {
defer func() {
waitGroup.Done()
}()
var mutex2 = redissonClient.NewMutex("redisson_mutex")
err = mutex2.Unlock(context.Background())
if err != nil {
t.Error(err)
return
}
t.Log("unlock successfully")
}()
waitGroup.Wait()
// 测试:加锁的协程可以顺利解锁
err = mutex1.Unlock(context.Background())
if err != nil {
t.Error(err)
return
}
t.Log("unlock successfully")
}