sse.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package util
  2. import (
  3. "app.yhyue.com/moapp/jybase/go-logger/logger"
  4. "app.yhyue.com/moapp/jybase/redis"
  5. "app.yhyue.com/moapp/message/model"
  6. "encoding/json"
  7. "fmt"
  8. "strings"
  9. "sync"
  10. )
  11. type Broadcast struct {
  12. Clients map[chan string]struct{}
  13. Mu sync.Mutex
  14. }
  15. var (
  16. SseBroadcast = &Broadcast{
  17. Clients: make(map[chan string]struct{}),
  18. }
  19. )
  20. // SendToUsers 消息通知
  21. func (s *Broadcast) SendToUsers(msg model.SseMessage) {
  22. s.Mu.Lock()
  23. defer s.Mu.Unlock()
  24. msgData, _ := json.Marshal(msg)
  25. for clientChan := range s.Clients {
  26. select {
  27. case clientChan <- string(msgData):
  28. logger.Info("send to all user, msg:", msg)
  29. default:
  30. logger.Info("Client channel full, skipping")
  31. }
  32. }
  33. }
  34. // 全局变量:存储所有用户的 SSE 连接
  35. var (
  36. SseClients = make(map[string]chan string) // 用户ID -> 消息通道
  37. SseClientsMu sync.Mutex // 保护 clients 的互斥锁
  38. )
  39. // 向指定用户发送通知
  40. func SendNotification(userId string, msg model.SseMessage) {
  41. //logger.Info(userId, "----SendNotification-----SseClients:", SseClients)
  42. SseClientsMu.Lock()
  43. defer SseClientsMu.Unlock()
  44. msgData, _ := json.Marshal(msg)
  45. if ch, ok := SseClients[userId]; ok {
  46. ch <- string(msgData)
  47. }
  48. }
  49. // 向所有用户发送通知
  50. func SendNotificationToAll(msg model.SseMessage) {
  51. //logger.Info("SendNotificationToAll ----- SseClients:", SseClients)
  52. SseClientsMu.Lock()
  53. defer SseClientsMu.Unlock()
  54. msgData, _ := json.Marshal(msg)
  55. for userId, ch := range SseClients {
  56. logger.Info("to all ; userId:", userId)
  57. ch <- string(msgData)
  58. }
  59. }
  60. const (
  61. sseRedisKey = "sse_cache_%s"
  62. powerCacheDb = "newother"
  63. expiresTime = 24 * 60 * 60
  64. )
  65. func SetSseRedisCache(userId, keys string) {
  66. cacheKey := fmt.Sprintf(sseRedisKey, userId)
  67. cacheData := redis.GetStr(powerCacheDb, cacheKey)
  68. var caches []string
  69. if cacheData == "" {
  70. caches = append(caches, userId, keys)
  71. } else {
  72. caches = append(strings.Split(cacheData, ","), keys)
  73. }
  74. redis.Put(powerCacheDb, cacheKey, strings.Join(caches, ","), expiresTime)
  75. }
  76. func GetSseRedisCache(userId string) (keys []string) {
  77. cacheKey := fmt.Sprintf(sseRedisKey, userId)
  78. cacheData := redis.GetStr(powerCacheDb, cacheKey)
  79. return strings.Split(cacheData, ",")
  80. }