3 Star 4 Fork 1

kelvins-io/common

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
redis_lock_v2.go 1.07 KB
一键复制 编辑 原始数据 按行查看 历史
cristiane 提交于 2020-08-01 11:47 . 初始v1
package lock
import (
"fmt"
"time"
"github.com/gomodule/redigo/redis"
)
type RedisLockInterface interface {
Set(*redis.Pool, string, uint32) (bool, string, error)
Release(*redis.Pool, string, string) error
}
type RedisLock struct{}
func (r *RedisLock) Set(redisPool *redis.Pool, key string, expireSecond uint32) (bool, string, error) {
if expireSecond == 0 {
return false, "", fmt.Errorf("expireSecond参数必须大于0")
}
conn := redisPool.Get()
defer conn.Close()
randVal := time.Now().Format("2006-01-02 15:04:05.000")
reply, err := conn.Do("SET", key, randVal, "NX", "PX", expireSecond*1000)
if err != nil {
return false, "", err
}
if reply == nil {
return false, "", nil
}
return true, randVal, nil
}
func (r *RedisLock) Release(redisPool *redis.Pool, key string, randVal string) error {
conn := redisPool.Get()
defer conn.Close()
luaScript := `
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end;
`
script := redis.NewScript(1, luaScript)
_, err := script.Do(conn, key, randVal)
return err
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/kelvins-io/common.git
git@gitee.com:kelvins-io/common.git
kelvins-io
common
common
v1.1.4

搜索帮助