@@ -0,0 +1,80 @@
|
||||
package synclock
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"91porn-server/common/redis"
|
||||
)
|
||||
|
||||
const (
|
||||
UserExtSyncLockFmt = "userExtSyncLock:%d" // 用户账户扩展信息
|
||||
UserExtSyncLockExpire = 5 * time.Minute // 用户账户扩展信息 过期时间
|
||||
UserAccountLockFmt = "UserAccountLockFmt:%d" // 用户账户
|
||||
SpinLockExpire = 3 * time.Second
|
||||
)
|
||||
|
||||
type Lock struct {
|
||||
Lock *redis.Client
|
||||
}
|
||||
|
||||
// UserExtSyncLock 通过redis按照用户ID加锁
|
||||
func (l *Lock) UserExtcLock(userId uint32) bool {
|
||||
v, e := l.Lock.Setnx_NewOK(fmt.Sprintf(UserExtSyncLockFmt, userId), true, UserExtSyncLockExpire)
|
||||
if !v || e != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// UserExtSpinLock 通过redis按照用户ID加锁
|
||||
func (l *Lock) UserExtSpinLock(userId uint32, lockTimeOut time.Duration) (bool, error) {
|
||||
endTime := time.Now().Add(lockTimeOut)
|
||||
for time.Now().Before(endTime) {
|
||||
value, err := l.Lock.Setnx_NewOK(fmt.Sprintf(UserExtSyncLockFmt, userId), true, UserExtSyncLockExpire)
|
||||
if err != nil {
|
||||
return false, errors.New("redis未启动")
|
||||
}
|
||||
if value {
|
||||
return true, nil
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
return false, errors.New("用户操作繁忙")
|
||||
}
|
||||
|
||||
// UserExtUnlock 按照用户ID释放锁
|
||||
func (l *Lock) UserExtUnlock(userId uint32) {
|
||||
_, _ = l.Lock.Del(fmt.Sprintf(UserExtSyncLockFmt, userId))
|
||||
}
|
||||
|
||||
// UserAccountLock 通过redis按照用户ID加锁
|
||||
func (l *Lock) UserAccountLock(userId uint32) bool {
|
||||
v, e := l.Lock.Setnx_NewOK(fmt.Sprintf(UserAccountLockFmt, userId), true, UserExtSyncLockExpire)
|
||||
if !v || e != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// UserAccountSpinLock 通过redis按照用户ID加锁
|
||||
func (l *Lock) UserAccountSpinLock(userId uint32, lockTimeOut time.Duration) (bool, error) {
|
||||
endTime := time.Now().Add(lockTimeOut)
|
||||
for time.Now().Before(endTime) {
|
||||
value, err := l.Lock.Setnx_NewOK(fmt.Sprintf(UserAccountLockFmt, userId), true, UserExtSyncLockExpire)
|
||||
if err != nil {
|
||||
return false, errors.New("redis未启动")
|
||||
}
|
||||
if value {
|
||||
return true, nil
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
return false, errors.New("用户操作繁忙")
|
||||
}
|
||||
|
||||
// UserAccountUnlock 按照用户ID释放锁
|
||||
func (l *Lock) UserAccountUnlock(userId uint32) {
|
||||
_, _ = l.Lock.Del(fmt.Sprintf(UserAccountLockFmt, userId))
|
||||
}
|
||||
Reference in New Issue
Block a user