servicecontext.go 5.5 KB

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