优化锁的使用
This commit is contained in:
@@ -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
|
||||||
|
}
|
||||||
@@ -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()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,6 +17,8 @@ type globalLock struct {
|
|||||||
value string
|
value string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
func NewGlobalLock(ctx context.Context, red redis.UniversalClient, uniqueKey string) *globalLock {
|
func NewGlobalLock(ctx context.Context, red redis.UniversalClient, uniqueKey string) *globalLock {
|
||||||
ctx, cancel := context.WithTimeout(ctx, opt.lockTimeout)
|
ctx, cancel := context.WithTimeout(ctx, opt.lockTimeout)
|
||||||
return &globalLock{
|
return &globalLock{
|
||||||
|
|||||||
Reference in New Issue
Block a user