package p import ( "app.yhyue.com/moapp/jybase/redis" "sync/atomic" "time" "app.yhyue.com/moapp/jybase/logger" ) type Lock struct { Key string Push string Match string E_C int64 E_I bool } // func (l *Lock) Lock(key string) { atomic.AddInt64(&l.E_C, 1) for { if l.E_I { break } v, err := redis.IncrByErr(l.Key, key) if err == nil { if v == 1 { if key == l.Match { redis.PutCKV(l.Key, l.Push, 1) } else if key == l.Push { redis.PutCKV(l.Key, l.Match, 1) } break } } else { logger.Error("lock redis inc error", err) } logger.Info("目前处于锁住状态,等待", key, "执行完成") time.Sleep(1 * time.Minute) } l.E_I = true } // func (l *Lock) UnLock() { if atomic.AddInt64(&l.E_C, -1) <= 0 { l.E_I = false l.Clear(l.Push, l.Match) } } // func (l *Lock) Clear(keys ...interface{}) { redis.Del(l.Key, keys...) }