1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- // Copyright 2019 getensh.com. All rights reserved.
- // Use of this source code is governed by getensh.com.
- package cache
- import (
- "sync"
- "time"
- )
- type Lock struct {
- Key string
- Ttl int64
- stop bool
- mutex sync.Mutex
- }
- // 监听过期
- func (lock *Lock) watchLock() {
- sleepTime := time.Duration(lock.Ttl * 2 / 3)
- for {
- time.Sleep(sleepTime * time.Second)
- lock.mutex.Lock()
- if lock.stop {
- lock.mutex.Unlock()
- return
- }
- redisCache.Expire(lock.Key, lock.Ttl)
- lock.mutex.Unlock()
- }
- }
- func (lock *Lock) stopWatch() {
- lock.stop = true
- }
- func (lock *Lock) RedisLock() bool {
- if lock.Key == "" {
- return false
- }
- res, err := redisCache.SetNxEx(lock.Key, "lock", lock.Ttl)
- // redis 操作失败
- if err != nil {
- return false
- }
- // 上锁成功
- if res {
- go lock.watchLock()
- return true
- }
- return false
- }
- func (lock *Lock) RedisUnlock() {
- // 释放分布式锁
- lock.mutex.Lock()
- defer lock.mutex.Unlock()
- lock.stopWatch()
- redisCache.Del(lock.Key)
- }
- func RedisLock(key string) bool {
- res, err := redisCache.SetNxEx(key, "lock", 60)
- // redis 操作失败
- if err != nil {
- return false
- }
- // 上锁成功
- if res {
- return true
- }
- return false
- }
- func RedisUnlock(key string) {
- // 释放分布式锁
- redisCache.Del(key)
- }
|