2 Star 0 Fork 0

TeamsHub/backend-gopkg

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
lock.go 939 Bytes
Copy Edit Raw Blame History
wuzheng0709 authored 2024-08-04 19:14 +08:00 . fix mod
package redis
import (
"context"
"time"
redis "github.com/redis/go-redis/v9"
)
type RedisLock struct {
conn redis.Cmdable
timeout time.Duration
key string
val string
}
var ctx = context.Background()
func NewRedisLock(conn redis.Cmdable, key, val string, timeout time.Duration) *RedisLock {
return &RedisLock{conn: conn, timeout: timeout, key: key, val: val}
}
// TryLock return true ===> Get the lock successfully
func (lock *RedisLock) TryLock() (bool, error) {
return lock.conn.SetNX(ctx, lock.key, lock.val, lock.timeout).Result()
}
func (lock *RedisLock) UnLock() error {
luaDel := redis.NewScript("if redis.call('get',KEYS[1]) == ARGV[1] then " +
"return redis.call('del',KEYS[1]) else return 0 end")
return luaDel.Run(ctx, lock.conn, []string{lock.key}, lock.val).Err()
}
func (lock *RedisLock) GetLockKey() string {
return lock.key
}
func (lock *RedisLock) GetLockVal() string {
return lock.val
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wuzheng0709/backend-gopkg.git
git@gitee.com:wuzheng0709/backend-gopkg.git
wuzheng0709
backend-gopkg
backend-gopkg
v1.5.24

Search