1234567891011121314151617181920212223242526272829303132333435 |
- package utils
- import (
- "github.com/jaryhe/gopkgs/cache"
- "time"
- )
- const Prefix = "lock"
- // interval try lock时间间隔 ms, tryCount try lock 的次数
- func RedisLock(key string, interval int, tryCount int) (bool, error) {
- if interval <= 0 {
- interval = 500
- }
- if tryCount <= 0 {
- tryCount = 10
- }
- key = Prefix+"-"+key
- for i := 0; i < tryCount; i++ {
- ok, err := cache.Redis().SetNxEx(key, "-", 10)
- if err != nil {
- return false, err
- }
- if ok {
- return true, nil
- }
- time.Sleep(time.Duration(interval)*time.Microsecond)
- }
- return false, nil
- }
- func RedisUnlock(key string) error {
- key = Prefix+"-"+key
- _, err := cache.Redis().Del(key)
- return err
- }
|