2025-02-28 16:00:16 +08:00
|
|
|
|
package distributed_lock
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
2025-03-07 16:16:26 +08:00
|
|
|
|
"errors"
|
2025-02-28 16:00:16 +08:00
|
|
|
|
"fmt"
|
|
|
|
|
|
"strings"
|
|
|
|
|
|
"sync"
|
|
|
|
|
|
"time"
|
|
|
|
|
|
|
2025-03-07 16:16:26 +08:00
|
|
|
|
"modelRT/distributedlock/constant"
|
2025-02-28 16:00:16 +08:00
|
|
|
|
luascript "modelRT/distributedlock/luascript"
|
2025-03-07 16:16:26 +08:00
|
|
|
|
"modelRT/logger"
|
2025-02-28 16:00:16 +08:00
|
|
|
|
|
|
|
|
|
|
"github.com/go-redis/redis"
|
|
|
|
|
|
uuid "github.com/google/uuid"
|
|
|
|
|
|
"go.uber.org/zap"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
const (
|
2025-03-06 16:35:36 +08:00
|
|
|
|
internalLockLeaseTime = uint64(30)
|
2025-02-28 16:00:16 +08:00
|
|
|
|
unlockMessage = 0
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2025-03-11 15:35:15 +08:00
|
|
|
|
// RedissionLockConfig define redission lock config
|
2025-02-28 16:00:16 +08:00
|
|
|
|
type RedissionLockConfig struct {
|
2025-03-11 15:35:15 +08:00
|
|
|
|
LockLeaseTime uint64
|
2025-02-28 16:00:16 +08:00
|
|
|
|
Prefix string
|
|
|
|
|
|
ChanPrefix string
|
2025-03-07 16:16:26 +08:00
|
|
|
|
TimeoutPrefix string
|
2025-02-28 16:00:16 +08:00
|
|
|
|
Key string
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
type redissionLocker struct {
|
2025-03-07 16:16:26 +08:00
|
|
|
|
lockLeaseTime uint64
|
2025-02-28 16:00:16 +08:00
|
|
|
|
token string
|
|
|
|
|
|
key string
|
2025-03-06 16:35:36 +08:00
|
|
|
|
waitChanKey string
|
2025-03-07 16:16:26 +08:00
|
|
|
|
needRefresh bool
|
2025-02-28 16:00:16 +08:00
|
|
|
|
exit chan struct{}
|
|
|
|
|
|
client *redis.Client
|
|
|
|
|
|
once *sync.Once
|
|
|
|
|
|
logger *zap.Logger
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-03-07 16:16:26 +08:00
|
|
|
|
func (rl *redissionLocker) Lock(timeout ...time.Duration) error {
|
2025-02-28 16:00:16 +08:00
|
|
|
|
if rl.exit == nil {
|
|
|
|
|
|
rl.exit = make(chan struct{})
|
|
|
|
|
|
}
|
2025-03-07 16:16:26 +08:00
|
|
|
|
result := rl.tryLock().(*constant.RedisResult)
|
|
|
|
|
|
if result.Code == constant.UnknownInternalError {
|
|
|
|
|
|
rl.logger.Error(result.OutputResultMessage())
|
|
|
|
|
|
return fmt.Errorf("get lock failed:%w", result)
|
2025-02-28 16:00:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-03-07 16:16:26 +08:00
|
|
|
|
if (result.Code == constant.LockSuccess) && rl.needRefresh {
|
2025-02-28 16:00:16 +08:00
|
|
|
|
rl.once.Do(func() {
|
2025-03-07 16:16:26 +08:00
|
|
|
|
// async refresh lock timeout unitl receive exit singal
|
2025-02-28 16:00:16 +08:00
|
|
|
|
go rl.refreshLockTimeout()
|
|
|
|
|
|
})
|
2025-03-07 16:16:26 +08:00
|
|
|
|
return nil
|
2025-02-28 16:00:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-03-07 16:16:26 +08:00
|
|
|
|
subMsg := make(chan struct{}, 1)
|
|
|
|
|
|
defer close(subMsg)
|
2025-03-06 16:35:36 +08:00
|
|
|
|
sub := rl.client.Subscribe(rl.waitChanKey)
|
2025-02-28 16:00:16 +08:00
|
|
|
|
defer sub.Close()
|
2025-03-07 16:16:26 +08:00
|
|
|
|
go rl.subscribeLock(sub, subMsg)
|
2025-02-28 16:00:16 +08:00
|
|
|
|
|
|
|
|
|
|
if len(timeout) > 0 && timeout[0] > 0 {
|
2025-03-07 16:16:26 +08:00
|
|
|
|
acquireTimer := time.NewTimer(timeout[0])
|
|
|
|
|
|
for {
|
2025-02-28 16:00:16 +08:00
|
|
|
|
select {
|
|
|
|
|
|
|
2025-03-07 16:16:26 +08:00
|
|
|
|
case _, ok := <-subMsg:
|
2025-02-28 16:00:16 +08:00
|
|
|
|
if !ok {
|
2025-03-07 16:16:26 +08:00
|
|
|
|
err := errors.New("failed to read the lock waiting for for the channel message")
|
|
|
|
|
|
rl.logger.Error("failed to read the lock waiting for for the channel message")
|
|
|
|
|
|
return err
|
2025-02-28 16:00:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-03-07 16:16:26 +08:00
|
|
|
|
resultErr := rl.tryLock().(*constant.RedisResult)
|
|
|
|
|
|
if (resultErr.Code == constant.LockFailure) || (resultErr.Code == constant.UnknownInternalError) {
|
|
|
|
|
|
rl.logger.Info(resultErr.OutputResultMessage())
|
|
|
|
|
|
continue
|
2025-02-28 16:00:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-03-07 16:16:26 +08:00
|
|
|
|
if resultErr.Code == constant.LockSuccess {
|
|
|
|
|
|
rl.logger.Info(resultErr.OutputResultMessage())
|
|
|
|
|
|
return nil
|
2025-02-28 16:00:16 +08:00
|
|
|
|
}
|
2025-03-07 16:16:26 +08:00
|
|
|
|
case <-acquireTimer.C:
|
|
|
|
|
|
err := errors.New("the waiting time for obtaining the lock operation has timed out")
|
|
|
|
|
|
rl.logger.Info("the waiting time for obtaining the lock operation has timed out")
|
|
|
|
|
|
return err
|
2025-02-28 16:00:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2025-03-07 16:16:26 +08:00
|
|
|
|
return fmt.Errorf("lock the redis lock failed:%w", result)
|
2025-02-28 16:00:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func (rl *redissionLocker) subscribeLock(sub *redis.PubSub, out chan struct{}) {
|
|
|
|
|
|
if sub == nil || out == nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-03-07 16:16:26 +08:00
|
|
|
|
rl.logger.Info("lock: enter sub routine", zap.String("token", rl.token))
|
|
|
|
|
|
|
2025-02-28 16:00:16 +08:00
|
|
|
|
for {
|
|
|
|
|
|
msg, err := sub.Receive()
|
|
|
|
|
|
if err != nil {
|
2025-03-07 16:16:26 +08:00
|
|
|
|
rl.logger.Info("sub receive message failed", zap.Error(err))
|
|
|
|
|
|
continue
|
2025-02-28 16:00:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
select {
|
|
|
|
|
|
case <-rl.exit:
|
2025-03-07 16:16:26 +08:00
|
|
|
|
break
|
2025-02-28 16:00:16 +08:00
|
|
|
|
default:
|
|
|
|
|
|
switch msg.(type) {
|
|
|
|
|
|
case *redis.Subscription:
|
|
|
|
|
|
// Ignore.
|
|
|
|
|
|
case *redis.Pong:
|
|
|
|
|
|
// Ignore.
|
|
|
|
|
|
case *redis.Message:
|
|
|
|
|
|
out <- struct{}{}
|
|
|
|
|
|
default:
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-03-07 16:16:26 +08:00
|
|
|
|
/*
|
|
|
|
|
|
KEYS[1]:锁的键名(key),通常是锁的唯一标识。
|
|
|
|
|
|
ARGV[1]:锁的过期时间(lockLeaseTime),单位为秒。
|
|
|
|
|
|
ARGV[2]:当前客户端的唯一标识(token),用于区分不同的客户端。
|
|
|
|
|
|
*/
|
2025-02-28 16:00:16 +08:00
|
|
|
|
func (rl *redissionLocker) refreshLockTimeout() {
|
2025-03-07 16:16:26 +08:00
|
|
|
|
rl.logger.Info("lock refresh by key and token", zap.String("token", rl.token), zap.String("key", rl.key))
|
|
|
|
|
|
|
|
|
|
|
|
lockTime := time.Duration(rl.lockLeaseTime/3) * time.Second
|
2025-02-28 16:00:16 +08:00
|
|
|
|
timer := time.NewTimer(lockTime)
|
|
|
|
|
|
defer timer.Stop()
|
2025-03-07 16:16:26 +08:00
|
|
|
|
|
2025-02-28 16:00:16 +08:00
|
|
|
|
for {
|
|
|
|
|
|
select {
|
|
|
|
|
|
case <-timer.C:
|
2025-03-07 16:16:26 +08:00
|
|
|
|
// extend key lease time
|
|
|
|
|
|
res := rl.client.Eval(luascript.RefreshLockScript, []string{rl.key}, rl.lockLeaseTime, rl.token)
|
2025-02-28 16:00:16 +08:00
|
|
|
|
val, err := res.Int()
|
2025-03-07 16:16:26 +08:00
|
|
|
|
if err != redis.Nil && err != nil {
|
|
|
|
|
|
rl.logger.Info("lock refresh failed", zap.String("token", rl.token), zap.String("key", rl.key), zap.Error(err))
|
|
|
|
|
|
return
|
2025-02-28 16:00:16 +08:00
|
|
|
|
}
|
2025-03-07 16:16:26 +08:00
|
|
|
|
|
|
|
|
|
|
if constant.RedisCode(val) == constant.RefreshLockFailure {
|
|
|
|
|
|
rl.logger.Error("lock refreash failed,can not find the lock by key and token", zap.String("token", rl.token), zap.String("key", rl.key))
|
|
|
|
|
|
break
|
2025-02-28 16:00:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-03-07 16:16:26 +08:00
|
|
|
|
if constant.RedisCode(val) == constant.RefreshLockSuccess {
|
|
|
|
|
|
rl.logger.Info("lock refresh success by key and token", zap.String("token", rl.token), zap.String("key", rl.key))
|
|
|
|
|
|
}
|
|
|
|
|
|
timer.Reset(lockTime)
|
|
|
|
|
|
case <-rl.exit:
|
|
|
|
|
|
break
|
2025-02-28 16:00:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func (rl *redissionLocker) cancelRefreshLockTime() {
|
|
|
|
|
|
if rl.exit != nil {
|
|
|
|
|
|
close(rl.exit)
|
|
|
|
|
|
rl.once = &sync.Once{}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-03-07 16:16:26 +08:00
|
|
|
|
/*
|
|
|
|
|
|
KEYS[1]:锁的键名(key),通常是锁的唯一标识。
|
|
|
|
|
|
ARGV[1]:锁的过期时间(lockLeaseTime),单位为秒。
|
|
|
|
|
|
ARGV[2]:当前客户端的唯一标识(token),用于区分不同的客户端。
|
|
|
|
|
|
*/
|
|
|
|
|
|
func (rl *redissionLocker) tryLock() error {
|
|
|
|
|
|
lockType := constant.LockType
|
|
|
|
|
|
res := rl.client.Eval(luascript.LockScript, []string{rl.key}, rl.lockLeaseTime, rl.token)
|
|
|
|
|
|
val, err := res.Int()
|
2025-02-28 16:00:16 +08:00
|
|
|
|
if err != redis.Nil && err != nil {
|
2025-03-07 16:16:26 +08:00
|
|
|
|
return constant.NewRedisResult(constant.UnknownInternalError, lockType, err.Error())
|
2025-02-28 16:00:16 +08:00
|
|
|
|
}
|
2025-03-07 16:16:26 +08:00
|
|
|
|
return constant.NewRedisResult(constant.RedisCode(val), lockType, "")
|
2025-02-28 16:00:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-03-07 16:16:26 +08:00
|
|
|
|
/*
|
|
|
|
|
|
KEYS[1]:锁的键名(key),通常是锁的唯一标识。
|
|
|
|
|
|
KEYS[2]:锁的释放通知频道(chankey),用于通知其他客户端锁已释放。
|
|
|
|
|
|
ARGV[1]:解锁消息(unlockMessage),用于通知其他客户端锁已释放。
|
|
|
|
|
|
ARGV[2]:当前客户端的唯一标识(token),用于区分不同的客户端。
|
|
|
|
|
|
*/
|
|
|
|
|
|
func (rl *redissionLocker) UnLock() error {
|
|
|
|
|
|
res := rl.client.Eval(luascript.UnLockScript, []string{rl.key, rl.waitChanKey}, unlockMessage, rl.token)
|
|
|
|
|
|
val, err := res.Int()
|
2025-02-28 16:00:16 +08:00
|
|
|
|
if err != redis.Nil && err != nil {
|
2025-03-07 16:16:26 +08:00
|
|
|
|
rl.logger.Info("unlock lock failed", zap.String("token", rl.token), zap.String("key", rl.key), zap.Error(err))
|
|
|
|
|
|
return fmt.Errorf("unlock lock failed:%w", constant.NewRedisResult(constant.UnknownInternalError, constant.UnLockType, err.Error()))
|
2025-02-28 16:00:16 +08:00
|
|
|
|
}
|
2025-03-07 16:16:26 +08:00
|
|
|
|
|
|
|
|
|
|
if constant.RedisCode(val) == constant.UnLockSuccess {
|
|
|
|
|
|
if rl.needRefresh {
|
|
|
|
|
|
rl.cancelRefreshLockTime()
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
rl.logger.Info("unlock lock success", zap.String("token", rl.token), zap.String("key", rl.key))
|
|
|
|
|
|
return nil
|
2025-02-28 16:00:16 +08:00
|
|
|
|
}
|
2025-03-07 16:16:26 +08:00
|
|
|
|
|
|
|
|
|
|
if constant.RedisCode(val) == constant.UnLocakFailureWithLockOccupancy {
|
|
|
|
|
|
rl.logger.Info("unlock lock failed", zap.String("token", rl.token), zap.String("key", rl.key))
|
|
|
|
|
|
return fmt.Errorf("unlock lock failed:%w", constant.NewRedisResult(constant.UnLocakFailureWithLockOccupancy, constant.UnLockType, ""))
|
2025-02-28 16:00:16 +08:00
|
|
|
|
}
|
2025-03-07 16:16:26 +08:00
|
|
|
|
return nil
|
2025-02-28 16:00:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func GetLocker(client *redis.Client, ops *RedissionLockConfig) *redissionLocker {
|
|
|
|
|
|
r := &redissionLocker{
|
2025-03-07 16:16:26 +08:00
|
|
|
|
token: uuid.New().String(),
|
|
|
|
|
|
needRefresh: true,
|
|
|
|
|
|
client: client,
|
|
|
|
|
|
exit: make(chan struct{}),
|
|
|
|
|
|
logger: logger.GetLoggerInstance(),
|
2025-02-28 16:00:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if len(ops.Prefix) <= 0 {
|
|
|
|
|
|
ops.Prefix = "redission-lock"
|
|
|
|
|
|
}
|
2025-03-07 16:16:26 +08:00
|
|
|
|
|
2025-02-28 16:00:16 +08:00
|
|
|
|
if len(ops.ChanPrefix) <= 0 {
|
|
|
|
|
|
ops.ChanPrefix = "redission-lock-channel"
|
|
|
|
|
|
}
|
2025-03-07 16:16:26 +08:00
|
|
|
|
|
2025-02-28 16:00:16 +08:00
|
|
|
|
if ops.LockLeaseTime == 0 {
|
|
|
|
|
|
r.lockLeaseTime = internalLockLeaseTime
|
|
|
|
|
|
}
|
|
|
|
|
|
r.key = strings.Join([]string{ops.Prefix, ops.Key}, ":")
|
2025-03-07 16:16:26 +08:00
|
|
|
|
r.waitChanKey = strings.Join([]string{ops.ChanPrefix, ops.Key, "wait"}, ":")
|
2025-02-28 16:00:16 +08:00
|
|
|
|
return r
|
|
|
|
|
|
}
|