You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/stores/redis/redislock.go

92 lines
1.8 KiB
Go

4 years ago
package redis
import (
"math/rand"
"sync/atomic"
"time"
red "github.com/go-redis/redis"
"github.com/tal-tech/go-zero/core/logx"
"github.com/tal-tech/go-zero/core/stringx"
4 years ago
)
const (
delCommand = `if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end`
randomLen = 16
4 years ago
)
// A RedisLock is a redis lock.
4 years ago
type RedisLock struct {
store *Redis
seconds uint32
count int32
4 years ago
key string
id string
}
func init() {
rand.Seed(time.Now().UnixNano())
}
// NewRedisLock returns a RedisLock.
4 years ago
func NewRedisLock(store *Redis, key string) *RedisLock {
return &RedisLock{
store: store,
key: key,
id: stringx.Randn(randomLen),
4 years ago
}
}
// Acquire acquires the lock.
4 years ago
func (rl *RedisLock) Acquire() (bool, error) {
newCount := atomic.AddInt32(&rl.count, 1)
if newCount > 1 {
return true, nil
}
4 years ago
seconds := atomic.LoadUint32(&rl.seconds)
ok, err := rl.store.SetnxEx(rl.key, rl.id, int(seconds+1)) // +1s for tolerance
4 years ago
if err == red.Nil {
atomic.AddInt32(&rl.count, -1)
4 years ago
return false, nil
} else if err != nil {
atomic.AddInt32(&rl.count, -1)
4 years ago
logx.Errorf("Error on acquiring lock for %s, %s", rl.key, err.Error())
return false, err
} else if !ok {
atomic.AddInt32(&rl.count, -1)
4 years ago
return false, nil
}
return true, nil
4 years ago
}
// Release releases the lock.
4 years ago
func (rl *RedisLock) Release() (bool, error) {
newCount := atomic.AddInt32(&rl.count, -1)
if newCount > 0 {
return true, nil
}
4 years ago
resp, err := rl.store.Eval(delCommand, []string{rl.key}, []string{rl.id})
if err != nil {
return false, err
}
reply, ok := resp.(int64)
if !ok {
4 years ago
return false, nil
}
return reply == 1, nil
4 years ago
}
// SetExpire sets the expiration.
4 years ago
func (rl *RedisLock) SetExpire(seconds int) {
atomic.StoreUint32(&rl.seconds, uint32(seconds))
}