onlin.go 1014 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package qznn
  2. import (
  3. "fmt"
  4. "sync"
  5. "time"
  6. "github.com/patrickmn/go-cache"
  7. "github.com/sirupsen/logrus"
  8. "gogs.daxia.dev/huanan/pkg.daxia.dev/parse"
  9. )
  10. var onlinUserCache *cache.Cache
  11. var onlinUserCacheLocker = sync.Mutex{}
  12. func getCacheInstance() *cache.Cache {
  13. onlinUserCacheLocker.Lock()
  14. defer onlinUserCacheLocker.Unlock()
  15. if onlinUserCache != nil {
  16. return onlinUserCache
  17. }
  18. onlinUserCache = cache.New(1*time.Minute, 2*time.Minute)
  19. onlinUserCache.OnEvicted(func(name string, val interface{}) {
  20. game := GetInstance()
  21. game.Leave(int32(parse.StringToInt64(name)), true)
  22. })
  23. return onlinUserCache
  24. }
  25. func UserIsOnline(userID uint) bool {
  26. _, exists := getCacheInstance().Get(fmt.Sprintf("%d", userID))
  27. return exists
  28. }
  29. func UserActive(userID uint) {
  30. logrus.Infof("UserActive:%d", userID)
  31. getCacheInstance().Set(fmt.Sprintf("%d", userID), 1, time.Minute)
  32. }
  33. func UserUnActive(userID uint) {
  34. logrus.Infof("UserUnActive:%d", userID)
  35. getCacheInstance().Delete(fmt.Sprintf("%d", userID))
  36. }