优化锁的使用

This commit is contained in:
Yun
2024-12-12 11:30:24 +08:00
parent 571b852c1a
commit cd0273f4b2
4 changed files with 69 additions and 0 deletions
+28
View File
@@ -0,0 +1,28 @@
package lockx
import (
"context"
"fmt"
"github.com/go-redis/redis/v8"
)
// 简单使用
var redisConn redis.UniversalClient
// 初始化redis连接
func Init(ctx context.Context, redis redis.UniversalClient, opts ...Option) error {
redisConn = redis
InitOption(opts...)
return nil
}
// 新起一个锁对象
// 先Init后New再Lock
func New(ctx context.Context, uniqueKey string) (*globalLock, error) {
if redisConn == nil {
return nil, fmt.Errorf("redis client is nil")
}
return NewGlobalLock(ctx, redisConn, uniqueKey), nil
}
+34
View File
@@ -0,0 +1,34 @@
package lockx_test
import (
"context"
"fmt"
"testing"
"github.com/go-redis/redis/v8"
"github.com/yuninks/lockx"
)
func TestSimpleLock(t *testing.T) {
ctx := context.Background()
client := redis.NewClient(&redis.Options{
Addr: "127.0.0.1" + ":" + "6379",
Password: "123456", // no password set
DB: 0, // use default DB
})
if client == nil {
fmt.Println("redis init error")
return
}
lockx.Init(ctx, client)
l, err := lockx.New(ctx, "lockx:test")
if err != nil {
t.Log(err)
return
}
if l.Lock() {
fmt.Println("lock success")
l.Unlock()
}
}
+2
View File
@@ -17,6 +17,8 @@ type globalLock struct {
value string
}
func NewGlobalLock(ctx context.Context, red redis.UniversalClient, uniqueKey string) *globalLock {
ctx, cancel := context.WithTimeout(ctx, opt.lockTimeout)
return &globalLock{
+5
View File
@@ -0,0 +1,5 @@
1.这个锁是基于redis的全局锁
2.在同一个new下边,多次加锁是可以重入的(因为值是一致)
3.多次加锁只要执行了一次释放,这个锁将会被释放