message.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package model
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "trading-go/common"
  7. )
  8. type Message struct {
  9. MsgType int `json:"msgType"`
  10. From uint `json:"from"`
  11. To uint `json:"to"`
  12. Time uint `json:"time"`
  13. Content any `json:"content"`
  14. }
  15. func (m Message) Save() {
  16. rds := common.Redis
  17. ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
  18. defer cancel()
  19. key := fmt.Sprintf("%d:%d:%d", m.From, m.To, m.Time)
  20. rds.Set(ctx, key, m, time.Second*60*60*24*30)
  21. }
  22. func (m Message) GetFrom(uid uint) (ms []Message, err error) {
  23. rds := common.Redis
  24. ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
  25. defer cancel()
  26. key := fmt.Sprintf("%d:*", uid)
  27. result, err := rds.Do(ctx, "MGET", key).Result()
  28. ms = result.([]Message)
  29. return
  30. }
  31. func (m Message) GetTo(uid uint) (ms []Message, err error) {
  32. rds := common.Redis
  33. ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
  34. defer cancel()
  35. key := fmt.Sprintf("*:%d:*", uid)
  36. result, err := rds.Do(ctx, "MGET", key).Result()
  37. ms = result.([]Message)
  38. return
  39. }