Skip to content

Commit ab371f4

Browse files
author
hero
committed
修改redis分布式加锁的方式
1 parent 5980f54 commit ab371f4

File tree

3 files changed

+12
-13
lines changed

3 files changed

+12
-13
lines changed

redis/lock/lock.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package lock
22

33
import (
4+
"context"
45
"github.com/go-redis/redis"
56
"time"
67
)
@@ -17,13 +18,12 @@ func NewRedisLock(conn *redis.Client, key, val string, timeout time.Duration) *R
1718
}
1819

1920
//return true ===> Get the lock successfully
20-
func (lock *RedisLock) TryLock() (bool, error) {
21-
//lock.conn.Do("SET",lock.key,lock.val,"EX",int(lock.timeout), "NX").Result()
22-
return lock.conn.SetNX(lock.key, lock.val, lock.timeout).Result()
21+
func (lock *RedisLock) TryLock() error {
22+
return lock.conn.Do(context.Background(), "set", lock.key, lock.val, "ex", int64(lock.timeout/time.Second), "nx").Err()
2323
}
2424

2525
func (lock *RedisLock) UnLock() error {
26-
return lock.conn.Del(lock.key).Err()
26+
return lock.conn.Del(context.Background(), lock.key).Err()
2727
}
2828

2929
func (lock *RedisLock) GetLockKey() string {

redis/lock/lock_server.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package lock
22

33
type RedisLockServer interface {
4-
TryLock() (bool, error)
4+
TryLock() error
55
UnLock() error
66
GetLockKey() string
77
GetLockVal() string

redis/lock/lock_test.go

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package lock
22

33
import (
4+
"context"
45
"fmt"
56
"github.com/go-redis/redis"
67
"testing"
@@ -19,26 +20,24 @@ func TestRedis(t *testing.T) {
1920
DB: 0,
2021
},
2122
)
22-
err := GlobalClient.Ping().Err()
23+
ping, err := GlobalClient.Ping(context.Background()).Result()
2324
if nil != err {
2425
panic(err)
2526
}
26-
redisLock := NewRedisLock(GlobalClient, "1", "2", time.Second*3)
27+
fmt.Println("ping", ping)
28+
redisLock := NewRedisLock(GlobalClient, "test", "1", time.Second*3)
2729
InitRedis(redisLock)
2830
select {}
2931
}
3032
func InitRedis(lock RedisLockServer) {
3133
go func() {
3234
for {
3335
time.Sleep(time.Second)
34-
succ, err := lock.TryLock()
36+
err := lock.TryLock()
3537
if err != nil {
36-
panic(err)
37-
}
38-
if succ {
39-
fmt.Println("获取锁成功")
40-
} else {
4138
fmt.Println("获取锁失败")
39+
} else {
40+
fmt.Println("获取锁成功")
4241
}
4342
}
4443
}()

0 commit comments

Comments
 (0)