You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.9 KiB
Go

package gift
import (
"dcg/config"
"dcg/game/pb"
pbMq "dcg/game/pb/mq"
"dcg/game/svc"
"dcg/pkg/kafka"
"dcg/pkg/logger"
"github.com/Shopify/sarama"
"github.com/golang/protobuf/proto"
)
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,
}, 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
}
h.ctx.RoomManager.Broadcast("game.gift", &pb.Gift{
User: &pb.User{
UId: msgFromMq.Uid,
Uname: msgFromMq.Uname,
},
GiftId: msgFromMq.GiftId,
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
}