Commit 5767da59 by yemin

no message

parent 293be8a5
...@@ -4,6 +4,7 @@ import ( ...@@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"git.168cad.top/go/logger/log" "git.168cad.top/go/logger/log"
"github.com/go-redis/redis" "github.com/go-redis/redis"
"math"
"time" "time"
) )
...@@ -128,6 +129,14 @@ var unlockScript string = `if redis.call('get', KEYS[1]) == ARGV[1] then ...@@ -128,6 +129,14 @@ var unlockScript string = `if redis.call('get', KEYS[1]) == ARGV[1] then
return "0" return "0"
end` end`
var hasKeyAndSetScript string = `if redis.call("exists",KEYS[1]) == 1 then
local lockSrc = redis.call("set",KEYS[1],unpack(ARGV))
if lockSrc then
return "1"
end
return "0"
end`
// Lock 抢锁。抢到锁返回true,否则false。只抢一次 // Lock 抢锁。抢到锁返回true,否则false。只抢一次
// 所有参数必传,超时时间单位秒 // 所有参数必传,超时时间单位秒
func Lock(k, uniqueValue string, timeoutSecond int) bool { func Lock(k, uniqueValue string, timeoutSecond int) bool {
...@@ -167,6 +176,42 @@ func LockWait(k, uniqueValue string, timeoutSecond int, lockTimeoutSecond int) b ...@@ -167,6 +176,42 @@ func LockWait(k, uniqueValue string, timeoutSecond int, lockTimeoutSecond int) b
return false return false
} }
// SetHasKey 有key时再更新值
func SetHasKey(k, v string) bool {
r, _ := getDb().Eval(lockScript, []string{k}, v).String()
if r == "1" {
return true
}
return false
}
// WaitSetHasKey 在一定是的次数范围内,一直满足 有key再更新
//k
//v
//loopTime 轮训休息时间 ms。默认100ms
//limit 最大轮训次数。不传时则不限制
func WaitSetHasKey(k, v string, loopTime, limit int64) bool {
if loopTime == 0 {
loopTime = 100
}
if limit == 0 {
limit = math.MaxInt64
}
count := int64(0)
locked := false
for !locked {
locked = SetHasKey(k, v)
count++
if count >= limit {
break
}
if !locked {
time.Sleep(time.Millisecond * time.Duration(loopTime))
}
}
return locked
}
// Hset 向一张hash表中放入数据,如果不存在将创建 // Hset 向一张hash表中放入数据,如果不存在将创建
func Hset(k, i, v string, timeoutSecond int) error { func Hset(k, i, v string, timeoutSecond int) error {
e := getDb().HSet(k, i, v).Err() e := getDb().HSet(k, i, v).Err()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment