package gift import ( "context" "dcg/app/user_center/pb" "dcg/config" pbMq "dcg/game/pb/mq" pushPb "dcg/game/pb/push" "dcg/game/svc" kfk "dcg/pkg/kafka" "git.noahlan.cn/northlan/ntools-go/kafka" "git.noahlan.cn/northlan/ntools-go/logger" "github.com/Shopify/sarama" "github.com/golang/protobuf/proto" "strconv" ) type MsgToPushHandler struct { ctx *svc.ServiceContext msgHandle map[string]msgHandlerFunc ConsumerGroup *kafka.ConsumerGroup } func (h *MsgToPushHandler) Init(ctx *svc.ServiceContext) { h.ctx = ctx cfg := config.Config.Kafka.Gift h.msgHandle = make(map[string]msgHandlerFunc) h.msgHandle["gift"] = h.handleGift var err error h.ConsumerGroup, err = kafka.NewConsumerGroup(&kafka.ConsumerGroupConfig{ KafkaVersion: sarama.V3_1_0_0, OffsetsInitial: sarama.OffsetNewest, IsReturnErr: false, UnMarshaler: kfk.ProtobufMarshaler, }, cfg.Addr, []string{cfg.Topic}, config.Config.ConsumerGroupId.GiftToPush) if err != nil { logger.SLog.Error(err) } } func (h *MsgToPushHandler) handleGift(data []byte, msgKey string) { // msg proto var msgFromMq pbMq.MqGift err := proto.Unmarshal(data, &msgFromMq) if err != nil { logger.SLog.Error("unmarshal msg err", err) return } // rpc创建或获取用户数据 pbUser := &pushPb.PushUser{ UId: msgFromMq.Uid, Uname: msgFromMq.Uname, } rpcUser, err := h.ctx.UserCenterRpc.RetrievePlatformUser(context.Background(), &pb.PlatformUserReq{ Platform: msgFromMq.Platform, PUid: strconv.FormatInt(msgFromMq.Uid, 10), }) if err == nil { pbUser.Avatar = rpcUser.User.PAvatar } else { logger.SLog.Error("rpc获取用户信息失败", err) } h.ctx.RoomManager.PushToRoom(msgFromMq.LiveRoomId, "game.gift", &pushPb.Gift{ User: pbUser, GiftId: msgFromMq.GiftId, Num: msgFromMq.Num, TotalCoin: msgFromMq.TotalCoin, }) logger.SLog.Debugf("队列礼物消息: %s 投喂 %s 价值 %d", msgFromMq.Uname, msgFromMq.GiftName, msgFromMq.TotalCoin) } func (MsgToPushHandler) Setup(_ sarama.ConsumerGroupSession) error { return nil } func (MsgToPushHandler) Cleanup(_ sarama.ConsumerGroupSession) error { return nil } func (h *MsgToPushHandler) ConsumeClaim(sess sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error { for msg := range claim.Messages() { //logger.SLog.Infow("kafka get info to mysql", "msgTopic", msg.Topic, "msgPartition", msg.Partition, "msg", string(msg.Value)) if hFunc, ok := h.msgHandle[msg.Topic]; ok { hFunc(msg.Value, string(msg.Key)) } sess.MarkMessage(msg, "") } return nil }