You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user_device_cache.go 1.1 KiB

1 month ago
1 month ago
1 month ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package device
  2. import (
  3. "egg-im/pkg/db"
  4. "egg-im/pkg/gerrors"
  5. "strconv"
  6. "time"
  7. "github.com/go-redis/redis"
  8. )
  9. const (
  10. UserDeviceKey = "user_device:"
  11. UserDeviceExpire = 2 * time.Hour
  12. )
  13. type userDeviceCache struct{}
  14. var UserDeviceCache = new(userDeviceCache)
  15. // Get 获取指定用户的所有在线设备
  16. func (c *userDeviceCache) Get(userId int64) ([]Device, error) {
  17. var devices []Device
  18. err := db.RedisUtil.Get(UserDeviceKey+strconv.FormatInt(userId, 10), &devices)
  19. if err != nil && err != redis.Nil {
  20. return nil, gerrors.WrapError(err)
  21. }
  22. if err == redis.Nil {
  23. return nil, nil
  24. }
  25. return devices, nil
  26. }
  27. // Set 将指定用户的所有在线设备存入缓存
  28. func (c *userDeviceCache) Set(userId int64, devices []Device) error {
  29. err := db.RedisUtil.Set(UserDeviceKey+strconv.FormatInt(userId, 10), devices, UserDeviceExpire)
  30. return gerrors.WrapError(err)
  31. }
  32. // Del 删除用户的在线设备列表
  33. func (c *userDeviceCache) Del(userId int64) error {
  34. key := UserDeviceKey + strconv.FormatInt(userId, 10)
  35. _, err := db.RedisCli.Del(key).Result()
  36. return gerrors.WrapError(err)
  37. }