servicecontext.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. package svc
  2. import (
  3. "context"
  4. "github.com/Shopify/sarama"
  5. "github.com/bytedance/sonic"
  6. "github.com/gookit/event"
  7. treemap "github.com/liyue201/gostl/ds/map"
  8. "github.com/robfig/cron/v3"
  9. "github.com/zeromicro/go-zero/core/logx"
  10. "go.opentelemetry.io/otel/attribute"
  11. "io/ioutil"
  12. "ylink/comm/globalkey"
  13. "ylink/comm/kafka"
  14. "ylink/comm/model"
  15. "ylink/comm/trace"
  16. "ylink/core/inner/rpc/internal/config"
  17. "ylink/core/inner/rpc/internal/ext"
  18. )
  19. type ServiceContext struct {
  20. Config config.Config
  21. KqMsgBoxProducer *kafka.Producer
  22. KqCmdBoxProducer *kafka.Producer
  23. KqMsgConsumerGroup *kafka.ConsumerGroup
  24. TimeoutCron *cron.Cron
  25. }
  26. func NewServiceContext(c config.Config) *ServiceContext {
  27. svcCtx := &ServiceContext{
  28. Config: c,
  29. KqMsgBoxProducer: kafka.NewKafkaProducer(c.KqMsgBoxProducerConf.Brokers, c.KqMsgBoxProducerConf.Topic),
  30. KqCmdBoxProducer: kafka.NewKafkaProducer(c.KqCmdBoxProducerConf.Brokers, c.KqCmdBoxProducerConf.Topic),
  31. KqMsgConsumerGroup: kafka.NewConsumerGroup(&kafka.ConsumerGroupConfig{
  32. KafkaVersion: sarama.V1_0_0_0,
  33. OffsetsInitial: sarama.OffsetNewest,
  34. IsReturnErr: false,
  35. },
  36. c.KqMsgBoxConsumerConf.Brokers,
  37. []string{c.KqMsgBoxConsumerConf.Topic},
  38. c.KqMsgBoxConsumerConf.GroupId),
  39. }
  40. go svcCtx.subscribe()
  41. fetchCsCenterInfo(c)
  42. return svcCtx
  43. }
  44. func (s *ServiceContext) Setup(_ sarama.ConsumerGroupSession) error {
  45. return nil
  46. }
  47. func (s *ServiceContext) Cleanup(_ sarama.ConsumerGroupSession) error {
  48. return nil
  49. }
  50. func (s *ServiceContext) ConsumeClaim(sess sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
  51. for msg := range claim.Messages() {
  52. if msg.Topic == s.Config.KqMsgBoxConsumerConf.Topic {
  53. s.handleMessage(sess, msg)
  54. }
  55. }
  56. return nil
  57. }
  58. func (s *ServiceContext) handleMessage(sess sarama.ConsumerGroupSession, msg *sarama.ConsumerMessage) {
  59. traceId := kafka.GetTraceFromHeader(msg.Headers)
  60. if len(traceId) == 0 {
  61. return
  62. }
  63. trace.RunOnTracing(traceId, func(ctx context.Context) {
  64. logx.WithContext(ctx).Infof("handle message: %s", msg.Value)
  65. var message model.KqMessage
  66. if err := sonic.Unmarshal(msg.Value, &message); err != nil {
  67. logx.WithContext(ctx).Errorf("unmarshal msg error: %v", err)
  68. return
  69. }
  70. if message.Opt != model.CMD_SEND_MESSAGE {
  71. // 指令异常
  72. return
  73. }
  74. trace.StartTrace(ctx, "InnerServer.handleMessage.SendMessage", func(ctx context.Context) {
  75. if len(message.ReceiverId) == 0 || message.ReceiverId == "" {
  76. // receiverId为空代表这条消息是玩家发送的
  77. // 玩家发的消息,先从connectedMap找对应的客服,没有则从vipMap找,都没有则丢弃信息不投递
  78. if playerInfo := ext.GetConnectedPlayerInfo(message.GameId, message.Uid); playerInfo != nil {
  79. message.ReceiverId = playerInfo.CsId
  80. } else {
  81. if playerInfo := ext.GetVipPlayer(message.GameId, message.Uid); playerInfo != nil {
  82. message.ReceiverId = playerInfo.CsId
  83. } else {
  84. message.ReceiverId = ""
  85. }
  86. }
  87. // 经过填补后receiver_id还是空的则有异常,丢弃信息不投递
  88. if len(message.ReceiverId) != 0 && message.ReceiverId != "" {
  89. logx.WithContext(ctx).Infof("receiver: %s", message.ReceiverId)
  90. kMsg, _ := sonic.MarshalString(message)
  91. s.KqMsgBoxProducer.SendMessage(ctx, kMsg, message.ReceiverId)
  92. } else {
  93. logx.WithContext(ctx).Errorf("can not find receiver of the sender")
  94. }
  95. } else {
  96. // receiverId不为空代表这条消息是客服发的
  97. s.KqMsgBoxProducer.SendMessage(ctx, string(msg.Value), message.ReceiverId)
  98. }
  99. sess.MarkMessage(msg, "")
  100. }, attribute.String("msg.key", string(msg.Key)))
  101. })
  102. }
  103. func (s *ServiceContext) subscribe() {
  104. go s.KqMsgConsumerGroup.RegisterHandleAndConsumer(s)
  105. // 注册事件
  106. event.On(globalkey.EventRemoveTimeoutJob, event.ListenerFunc(func(e event.Event) error {
  107. logx.Info("on event remove timeout job...")
  108. entryId := e.Get("entry_id").(cron.EntryID)
  109. s.TimeoutCron.Remove(entryId)
  110. return nil
  111. }), event.High)
  112. // 初始化定时任务
  113. s.TimeoutCron = cron.New(cron.WithSeconds())
  114. s.TimeoutCron.Start()
  115. }
  116. func fetchCsCenterInfo(c config.Config) {
  117. // mock info
  118. ext.CsInfoMap = treemap.New(treemap.WithGoroutineSafe())
  119. ext.GameVipMap = treemap.New(treemap.WithGoroutineSafe())
  120. ext.GameOnlinePlayerMap = treemap.New(treemap.WithGoroutineSafe())
  121. ext.GameConnectedMap = treemap.New(treemap.WithGoroutineSafe())
  122. ext.WaitingQueue = treemap.New(treemap.WithGoroutineSafe())
  123. go loadMockInfo(c)
  124. }
  125. func loadMockInfo(c config.Config) {
  126. // 加载游戏列表
  127. logx.Info("加载游戏列表")
  128. var gameIds []string
  129. gameIdsData, err := ioutil.ReadFile(c.MockFolder + "/game_id.json")
  130. if err != nil {
  131. logx.Errorf("parse game_id.json has some error: %v", err)
  132. return
  133. }
  134. if err := sonic.Unmarshal(gameIdsData, &gameIds); err != nil {
  135. return
  136. }
  137. // 加载vip玩家信息
  138. logx.Info("加载vip玩家信息")
  139. for _, gameId := range gameIds {
  140. vipPlayerMap := treemap.New(treemap.WithGoroutineSafe())
  141. var playerInfos []*model.PlayerInfo
  142. playerInfosData, _ := ioutil.ReadFile(c.MockFolder + "/" + gameId + ".json")
  143. if err := sonic.Unmarshal(playerInfosData, &playerInfos); err != nil {
  144. return
  145. }
  146. for _, playerInfo := range playerInfos {
  147. vipPlayerMap.Insert(playerInfo.PlayerId, playerInfo)
  148. }
  149. ext.GameVipMap.Insert(gameId, vipPlayerMap)
  150. }
  151. // 加载客服信息
  152. logx.Info("加载客服信息")
  153. var csInfos []*model.CsInfo
  154. csInfosData, err := ioutil.ReadFile(c.MockFolder + "/cs_info.json")
  155. if err := sonic.Unmarshal(csInfosData, &csInfos); err != nil {
  156. return
  157. }
  158. for _, csInfo := range csInfos {
  159. ext.CsInfoMap.Insert(csInfo.CsId, csInfo)
  160. }
  161. }