1 Star 0 Fork 0

micro-tools/wf

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
gmredis_lock.go 1.59 KB
一键复制 编辑 原始数据 按行查看 历史
545403892 提交于 2023-09-27 22:16 +08:00 . 升级go-ole
package gmredis
import (
"fmt"
"time"
"gitee.com/micro-tools/wf/util/gconv"
"gitee.com/micro-tools/wf/util/guid"
)
type Lock struct {
}
//LockWithTimeout 设置分布式 lockTime 锁设置的ttl时间 ; waitTime 等待时间
func (c *Lock) LockWithTimeout(key string, lockTime, waitTime int) (string, bool) {
id := guid.S()
name := "lock:" + key
end := time.Now().Add(time.Second * time.Duration(waitTime))
for time.Now().Before(end) {
res, err := Get().Str.SetNX(name, id)
if err != nil {
return "", false
} else {
if res {
res, err = Get().Key.Expire(name, lockTime)
if err != nil {
return "", false
} else {
if res {
return id, true
} else {
return "", false
}
}
} else {
n, err := Get().Key.TTl(name)
if err != nil {
return "", false
}
if n == -1 {
// 如果key存在,但是没有设置剩余时间
_, _ = Get().Key.Expire(name, lockTime)
}
}
}
time.Sleep(time.Microsecond)
}
return "", false
}
//ReleaseLock 释放锁 id LockWithTimeout 返回的记录,用于比较存储中的一致性
func (c *Lock) ReleaseLock(key, id string) error {
name := "lock:" + key
has, err := Get().Key.Exists(name)
if err != nil {
return err
}
if has {
res, err := Get().Str.Get(name)
if err != nil {
return err
}
if id == gconv.String(res) {
_, _ = Get().Key.Del(name)
return nil
} else {
return fmt.Errorf("id %s != %s", id, gconv.String(res))
}
} else {
return fmt.Errorf("key %s is not exist", key)
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/micro-tools/wf.git
git@gitee.com:micro-tools/wf.git
micro-tools
wf
wf
v1.0.2

搜索帮助