cache.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package userCache
  2. import (
  3. "log"
  4. "sync"
  5. "time"
  6. )
  7. type UserCache struct {
  8. Lock sync.Mutex
  9. AccessCount int
  10. LastAccess time.Time
  11. }
  12. var lockCache sync.Map
  13. // 根据手机号获取或者创建锁
  14. func GetOrCreateUserCache(phone string) (userCache *UserCache) {
  15. if value, exists := lockCache.Load(phone); exists {
  16. userCache = value.(*UserCache)
  17. userCache.Lock.Lock()
  18. userCache.LastAccess = time.Now()
  19. userCache.AccessCount++
  20. userCache.Lock.Unlock()
  21. return userCache
  22. }
  23. userCache = &UserCache{
  24. Lock: sync.Mutex{},
  25. AccessCount: 0,
  26. LastAccess: time.Now(),
  27. }
  28. _, loaded := lockCache.LoadOrStore(phone, userCache)
  29. if !loaded {
  30. log.Println("load or store false,", phone)
  31. }
  32. return
  33. }
  34. // 获取手机号访问次数
  35. func GetAccessCount(phone string) int {
  36. userCache := GetOrCreateUserCache(phone)
  37. userCache.Lock.Lock()
  38. defer userCache.Lock.Unlock()
  39. return userCache.AccessCount
  40. }
  41. //// 增加手机号访问次数
  42. //func IncrementAccessCount(phone string) {
  43. // userCache := GetOrCreateUserCache(phone)
  44. // userCache.Lock.Lock()
  45. // defer userCache.Lock.Unlock()
  46. // userCache.AccessCount++
  47. // userCache.LastAccess = time.Now()
  48. //}
  49. // 清理过期缓存
  50. func ClearExpireCache() {
  51. lockCache.Range(func(key, value any) bool {
  52. userCache := value.(*UserCache)
  53. userCache.Lock.Lock()
  54. lastAccess := userCache.LastAccess
  55. userCache.Lock.Unlock()
  56. if time.Since(lastAccess) > 24*60*60 {
  57. lockCache.Delete(key)
  58. }
  59. return true
  60. })
  61. }
  62. // RunTimedTask .
  63. func RunTimedTask() {
  64. ticker := time.NewTicker(time.Minute * 30)
  65. go func() {
  66. for range ticker.C {
  67. ClearExpireCache()
  68. }
  69. }()
  70. }