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.
 
 
 
 

95 lines
2.2 KiB

  1. package room
  2. import (
  3. "egg-im/pkg/db"
  4. "egg-im/pkg/gerrors"
  5. "egg-im/pkg/pb"
  6. "egg-im/pkg/util"
  7. "fmt"
  8. "strconv"
  9. "time"
  10. "github.com/go-redis/redis"
  11. "google.golang.org/protobuf/proto"
  12. )
  13. const RoomMessageKey = "room_message:%d"
  14. const RoomMessageExpireTime = 2 * time.Minute
  15. type roomMessageRepo struct{}
  16. var RoomMessageRepo = new(roomMessageRepo)
  17. // Add 将消息添加到队列
  18. func (*roomMessageRepo) Add(roomId int64, msg *pb.Message) error {
  19. key := fmt.Sprintf(RoomMessageKey, roomId)
  20. buf, err := proto.Marshal(msg)
  21. if err != nil {
  22. return gerrors.WrapError(err)
  23. }
  24. _, err = db.RedisCli.ZAdd(key, redis.Z{
  25. Score: float64(msg.Seq),
  26. Member: buf,
  27. }).Result()
  28. db.RedisCli.Expire(key, RoomMessageExpireTime)
  29. if err != nil {
  30. return gerrors.WrapError(err)
  31. }
  32. return nil
  33. }
  34. // List 获取指定房间序列号大于seq的消息
  35. func (*roomMessageRepo) List(roomId int64, seq int64) ([]*pb.Message, error) {
  36. key := fmt.Sprintf(RoomMessageKey, roomId)
  37. result, err := db.RedisCli.ZRangeByScore(key, redis.ZRangeBy{
  38. Min: strconv.FormatInt(seq, 10),
  39. Max: "+inf",
  40. }).Result()
  41. if err != nil {
  42. return nil, gerrors.WrapError(err)
  43. }
  44. var msgs []*pb.Message
  45. for i := range result {
  46. buf := util.Str2bytes(result[i])
  47. var msg pb.Message
  48. err = proto.Unmarshal(buf, &msg)
  49. if err != nil {
  50. return nil, gerrors.WrapError(err)
  51. }
  52. msgs = append(msgs, &msg)
  53. }
  54. return msgs, nil
  55. }
  56. func (*roomMessageRepo) ListByIndex(roomId int64, start, stop int64) ([]*pb.Message, error) {
  57. key := fmt.Sprintf(RoomMessageKey, roomId)
  58. result, err := db.RedisCli.ZRange(key, start, stop).Result()
  59. if err != nil {
  60. return nil, gerrors.WrapError(err)
  61. }
  62. var msgs []*pb.Message
  63. for i := range result {
  64. buf := util.Str2bytes(result[i])
  65. var msg pb.Message
  66. err = proto.Unmarshal(buf, &msg)
  67. if err != nil {
  68. return nil, gerrors.WrapError(err)
  69. }
  70. msgs = append(msgs, &msg)
  71. }
  72. return msgs, nil
  73. }
  74. func (*roomMessageRepo) DelBySeq(roomId int64, min, max int64) error {
  75. if min == 0 && max == 0 {
  76. return nil
  77. }
  78. key := fmt.Sprintf(RoomMessageKey, roomId)
  79. _, err := db.RedisCli.ZRemRangeByScore(key, strconv.FormatInt(min, 10), strconv.FormatInt(max, 10)).Result()
  80. return gerrors.WrapError(err)
  81. }