forked from all_user/stat_center
64 lines
1.1 KiB
Go
64 lines
1.1 KiB
Go
package utils
|
|
|
|
import (
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type ExpiredLock struct {
|
|
items map[string]time.Time
|
|
lock sync.RWMutex
|
|
}
|
|
|
|
func NewExpiredLock() *ExpiredLock {
|
|
return &ExpiredLock{
|
|
items: make(map[string]time.Time),
|
|
}
|
|
}
|
|
|
|
func (kl *ExpiredLock) Count() int64 {
|
|
kl.lock.RLock()
|
|
defer kl.lock.RUnlock()
|
|
return int64(len(kl.items))
|
|
}
|
|
|
|
func (kl *ExpiredLock) LockedCount() int64 {
|
|
kl.lock.RLock()
|
|
defer kl.lock.RUnlock()
|
|
now := time.Now()
|
|
count := int64(0)
|
|
for _, expired := range kl.items {
|
|
if now.Before(expired) {
|
|
count++
|
|
}
|
|
}
|
|
return count
|
|
}
|
|
|
|
func (kl *ExpiredLock) UnLock(key string, expired time.Time) {
|
|
kl.lock.Lock()
|
|
defer kl.lock.Unlock()
|
|
expire, exists := kl.items[key]
|
|
if !exists || expire != expired {
|
|
return
|
|
}
|
|
delete(kl.items, key)
|
|
}
|
|
|
|
func (kl *ExpiredLock) TryLock(key string, expired time.Time) bool {
|
|
kl.lock.Lock()
|
|
defer kl.lock.Unlock()
|
|
expire, exists := kl.items[key]
|
|
if !exists {
|
|
kl.items[key] = expired
|
|
return true
|
|
} else {
|
|
if time.Now().After(expire) {
|
|
kl.items[key] = expired
|
|
return true
|
|
} else {
|
|
return false
|
|
}
|
|
}
|
|
}
|