golang-im聊天
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.

auth_cache.go 1.6 KiB

2 年之前
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package repo
  2. import (
  3. "encoding/json"
  4. "gim/internal/business/domain/user/model"
  5. "gim/pkg/db"
  6. "gim/pkg/gerrors"
  7. "gim/pkg/util"
  8. "strconv"
  9. "github.com/go-redis/redis"
  10. )
  11. const (
  12. AuthKey = "auth:"
  13. )
  14. type authCache struct{}
  15. var AuthCache = new(authCache)
  16. func (*authCache) Get(userId, deviceId int64) (*model.Device, error) {
  17. bytes, err := db.RedisCli.HGet(AuthKey+strconv.FormatInt(userId, 10), strconv.FormatInt(deviceId, 10)).Bytes()
  18. if err != nil && err != redis.Nil {
  19. return nil, gerrors.WrapError(err)
  20. }
  21. if err == redis.Nil {
  22. return nil, nil
  23. }
  24. var device model.Device
  25. err = json.Unmarshal(bytes, &device)
  26. if err != nil {
  27. return nil, gerrors.WrapError(err)
  28. }
  29. return &device, nil
  30. }
  31. func (*authCache) Set(userId, deviceId int64, device model.Device) error {
  32. bytes, err := json.Marshal(device)
  33. if err != nil {
  34. return gerrors.WrapError(err)
  35. }
  36. _, err = db.RedisCli.HSet(AuthKey+strconv.FormatInt(userId, 10), strconv.FormatInt(deviceId, 10), bytes).Result()
  37. if err != nil {
  38. return gerrors.WrapError(err)
  39. }
  40. return nil
  41. }
  42. func (*authCache) GetAll(userId int64) (map[int64]model.Device, error) {
  43. result, err := db.RedisCli.HGetAll(AuthKey + strconv.FormatInt(userId, 10)).Result()
  44. if err != nil {
  45. return nil, gerrors.WrapError(err)
  46. }
  47. var devices = make(map[int64]model.Device, len(result))
  48. for k, v := range result {
  49. deviceId, err := strconv.ParseInt(k, 10, 64)
  50. if err != nil {
  51. return nil, gerrors.WrapError(err)
  52. }
  53. var device model.Device
  54. err = json.Unmarshal(util.Str2bytes(v), &device)
  55. if err != nil {
  56. return nil, gerrors.WrapError(err)
  57. }
  58. devices[deviceId] = device
  59. }
  60. return devices, nil
  61. }