Fetch the repository succeeded.
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
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。