-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdlock_by_redis_test.go
59 lines (48 loc) · 1.08 KB
/
dlock_by_redis_test.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
54
55
56
57
58
59
package dlock
import (
"fmt"
"math/rand"
"sync"
"testing"
"time"
"github.com/petermattis/goid"
"github.com/stretchr/testify/assert"
)
var (
fakeRedisConnPoolConfig = &RedisConnPoolConfig{
RedisEndpoint: "127.0.0.1:6379",
RedisDatabase: 0,
RedisPassword: "sOmE_sEcUrE_pAsS",
RedisConnectTimeout: 2000,
RedisReadTimeout: 1000,
RedisWriteTimeout: 1000,
}
)
func TestDlockByRedis(t *testing.T) {
SkipAutoTest(t)
rand.Seed(time.Now().UnixNano())
conn := EstablishRedisConn(fakeRedisConnPoolConfig)
defer conn.Close()
total := 0
wg := &sync.WaitGroup{}
for i := 0; i < 20; i++ {
wg.Add(1)
go func(conn *RedisConnPool) {
defer wg.Done()
pid := fmt.Sprintf("%d", goid.Get())
dl := NewDlockByRedis(conn)
for {
token, acquired := dl.TryLock(pid, 30000, 2)
if acquired {
defer dl.Unlock(pid, token)
total++
time.Sleep(time.Millisecond * time.Duration(10+rand.Intn(10)))
break
}
time.Sleep(time.Millisecond * time.Duration(10+rand.Intn(10)))
}
}(conn)
}
wg.Wait()
assert.Equal(t, 20, total)
}