goRedisDLM/redisLock/lock_test.go

62 lines
967 B
Go

package redisLock
import (
"context"
"sync"
"testing"
"github.com/go-redis/redis/v8"
)
func Test_blockingLock(t *testing.T) {
addr := "192.168.8.1:6379"
passwd := ""
client := redis.NewClient(&redis.Options{
Addr: addr,
Password: passwd,
})
ctx := context.Background()
lock1 := NewRedisLock(client, ctx, "test_key", WithExpireTime(10))
lock2 := NewRedisLock(client, ctx, "test_key",
WithBlock(), WithExpireTime(5), WithMaxWaitTime(0))
var wg sync.WaitGroup
wg.Add(1)
go func() {
var err error
defer wg.Done()
defer func() {
if err == nil {
if err = lock1.UnLock(); err != nil {
t.Error(err)
}
}
}()
if err = lock1.Lock(); err != nil {
t.Error(err)
return
}
}()
wg.Add(1)
go func() {
defer wg.Done()
defer func() {
if err := lock2.UnLock(); err != nil {
t.Error(err)
}
}()
if err := lock2.Lock(); err != nil {
t.Error(err)
return
}
}()
wg.Wait()
t.Log("success")
}