Files
go-zero/core/stores/redis/redislock.go

92 lines
1.8 KiB
Go
Raw Normal View History

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