Skip to content

Commit

Permalink
修改锁的单元测试
Browse files Browse the repository at this point in the history
  • Loading branch information
steden committed Sep 9, 2022
1 parent df5fe0c commit 2179e42
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 22 deletions.
6 changes: 5 additions & 1 deletion redisLock.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package redis

import (
"github.com/farseer-go/fs/flog"
"github.com/go-redis/redis/v8"
"time"
)
Expand Down Expand Up @@ -28,7 +29,10 @@ func (r redisLock) GetLocker(key string, expiration time.Duration) lockResult {
// TryLock 尝试加锁
func (r *lockResult) TryLock() bool {
cmd := r.rdb.SetNX(ctx, r.key, 1, r.expiration)
result, _ := cmd.Result()
result, err := cmd.Result()
if err != nil {
flog.Errorf("redis加锁异常:%s", err.Error())
}
return result
}

Expand Down
36 changes: 15 additions & 21 deletions redisLock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,28 @@ package redis
import (
"github.com/farseer-go/fs/configure"
"github.com/farseer-go/fs/flog"
"github.com/farseer-go/fs/stopwatch"
"github.com/stretchr/testify/assert"
"testing"
"time"
)

func Test_lockResult_Lock(t *testing.T) {
configure.SetDefault("Redis.default", "Server=localhost:6379,DB=15,Password=redis123,ConnectTimeout=600000,SyncTimeout=10000,ResponseTimeout=10000")
//configure.SetDefault("Redis.default", "Server=localhost:6379,DB=15,Password=redis123,ConnectTimeout=600000,SyncTimeout=10000,ResponseTimeout=10000")
configure.SetDefault("Redis.default", "Server=192.168.1.8:6379,DB=15,Password=steden@123,ConnectTimeout=600000,SyncTimeout=10000,ResponseTimeout=10000")
client := NewClient("default")
local := client.Lock.GetLocker("key_local", time.Duration(1000))
control01(local)
go control02(local)
time.Sleep(time.Duration(100))
}

func control01(local lockResult) {
if !local.TryLock() {
flog.Println("-----01加锁失败")
}
defer local.ReleaseLock()
for i := 0; i < 10; i++ {
flog.Println("-----值:a", i)
for i := 0; i < 100; i++ {
control01(t, client)
}
}
func control02(local lockResult) {
if !local.TryLock() {
flog.Println("-----02加锁失败")
}

func control01(t *testing.T, client *Client) {
sw := stopwatch.StartNew()
local := client.Lock.GetLocker("key_local", 2*time.Second)
defer local.ReleaseLock()
for i := 0; i < 10; i++ {
flog.Println("-----值:b", i)
}
defer func() {
flog.Infof("GetLocker,耗时:%s", sw.GetMillisecondsText())
}()
assert.True(t, local.TryLock())
assert.False(t, local.TryLock())
}

0 comments on commit 2179e42

Please sign in to comment.