go使用redis锁
- 基于Redis的SetNX方法,创建并使用redis锁
- 曾经在一便文档中,有一句话,引发的我的思考:
如果公司内已有可以使用的ZooKeeper、etcd或者Redis集群,那么就尽量在不引入新的技术栈的情况下满足业务需求。
- 各种各样的分布式锁封装得实在太多,眼花缭乱,但如果项目使用到了redis,何不直接使用redis锁呢?
redis锁的封装
package redisLock
import (
"errors"
"github.com/go-redis/redis"
"github.com/google/uuid"
"sync"
"time"
)
type (
RedisLock struct {
lockChan chan struct{
}
rwLock sync.RWMutex
lockKey string
lockValue string
client *redis.Client
}
InvokeMethod func(args ...interface{
}) (interface{
}, error)
)
func NewRedisLock(client *redis.Client) *RedisLock {
return &RedisLock{
lockChan: make(chan struct{
}, 1),
lockKey: uuid.NewString(),
client: client,
}
}
func (this *RedisLock) TryLock(method InvokeMethod, timeout time.Duration) (interface{
}, error) {
this.rwLock.Lock()
defer this.rwLock.Unlock()
var err error
go <