temp
This commit is contained in:
37
Server/common/db/redis/redis_lock.go
Normal file
37
Server/common/db/redis/redis_lock.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"common/log"
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ReleaseLockExpire = errors.New("release redis lock expire key")
|
||||
|
||||
func Acquire(ctx context.Context, key string, tag string, expiration time.Duration) (bool, error) {
|
||||
success, err := redisClient.SetNX(ctx, key, tag, expiration).Result()
|
||||
return success, err
|
||||
}
|
||||
|
||||
func Release(ctx context.Context, key string, tag string) error {
|
||||
script := `
|
||||
if redis.call("GET", KEYS[1]) == ARGV[1] then
|
||||
return redis.call("DEL", KEYS[1])
|
||||
else
|
||||
return 0
|
||||
end`
|
||||
|
||||
// 执行 Lua 脚本
|
||||
result, err := redisClient.Eval(ctx, script, []string{key}, tag).Result()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// 检查返回值
|
||||
if result == int64(0) {
|
||||
log.Errorf("release redis lock expire key :%v", key)
|
||||
return ReleaseLockExpire
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user