onlin.go 908 B

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