123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- package userCache
- import (
- "log"
- "sync"
- "time"
- )
- type UserCache struct {
- Lock sync.Mutex
- AccessCount int
- LastAccess time.Time
- }
- var lockCache sync.Map
- // 根据手机号获取或者创建锁
- func GetOrCreateUserCache(phone string) (userCache *UserCache) {
- if value, exists := lockCache.Load(phone); exists {
- userCache = value.(*UserCache)
- userCache.Lock.Lock()
- userCache.LastAccess = time.Now()
- userCache.AccessCount++
- userCache.Lock.Unlock()
- return userCache
- }
- userCache = &UserCache{
- Lock: sync.Mutex{},
- AccessCount: 0,
- LastAccess: time.Now(),
- }
- _, loaded := lockCache.LoadOrStore(phone, userCache)
- if !loaded {
- log.Println("load or store false,", phone)
- }
- return
- }
- // 获取手机号访问次数
- func GetAccessCount(phone string) int {
- userCache := GetOrCreateUserCache(phone)
- userCache.Lock.Lock()
- defer userCache.Lock.Unlock()
- return userCache.AccessCount
- }
- //// 增加手机号访问次数
- //func IncrementAccessCount(phone string) {
- // userCache := GetOrCreateUserCache(phone)
- // userCache.Lock.Lock()
- // defer userCache.Lock.Unlock()
- // userCache.AccessCount++
- // userCache.LastAccess = time.Now()
- //}
- // 清理过期缓存
- func ClearExpireCache() {
- lockCache.Range(func(key, value any) bool {
- userCache := value.(*UserCache)
- userCache.Lock.Lock()
- lastAccess := userCache.LastAccess
- userCache.Lock.Unlock()
- if time.Since(lastAccess) > 24*60*60 {
- lockCache.Delete(key)
- }
- return true
- })
- }
- // RunTimedTask .
- func RunTimedTask() {
- ticker := time.NewTicker(time.Minute * 30)
- go func() {
- for range ticker.C {
- ClearExpireCache()
- }
- }()
- }
|