package danmaku import ( "dcg/config" "dcg/game/command" "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" "regexp" ) type MsgToDbHandler struct { ctx *svc.ServiceContext msgHandle map[string]msgHandlerFunc regex *regexp.Regexp commandManager *command.Manager ConsumerGroup *kafka.ConsumerGroup } func (h *MsgToDbHandler) Init(ctx *svc.ServiceContext) { h.ctx = ctx cfg := config.Config.Kafka.Danmaku h.msgHandle = make(map[string]msgHandlerFunc) h.msgHandle["danmaku"] = h.handleDanmaku h.commandManager = command.NewManager() h.commandManager.Register("j", h.handleAllCmd) h.commandManager.Register("c", h.handleAllCmd) h.commandManager.Register("s", h.handleAllCmd) h.commandManager.Register("m", h.handleAllCmd) h.commandManager.Register("w", h.handleAllCmd) var err error h.regex, err = regexp.Compile(config.Config.Command.Regex) if err != nil { logger.SLog.Error(err) } 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.MsgToDb) if err != nil { logger.SLog.Error(err) } } func (h *MsgToDbHandler) handleAllCmd(_ string, user *pb.User) { } func (h *MsgToDbHandler) handleDanmaku(data []byte, msgKey string) { // danmaku msg proto var msgFromMq pbMq.MqDanmaku err := proto.Unmarshal(data, &msgFromMq) if err != nil { logger.SLog.Error("unmarshal msg err", err) return } cmdArr := h.parseCommands(msgFromMq.Content) for _, cmd := range cmdArr { h.commandManager.Handle(cmd, &pb.User{ UId: msgFromMq.Uid, Uname: msgFromMq.Uname, }) } } func (h *MsgToDbHandler) parseCommands(msg string) []string { if h.regex == nil { logger.SLog.Error("regex is null") return []string{} } return h.regex.FindAllString(msg, -1) } func (MsgToDbHandler) Setup(_ sarama.ConsumerGroupSession) error { return nil } func (MsgToDbHandler) Cleanup(_ sarama.ConsumerGroupSession) error { return nil } func (h *MsgToDbHandler) ConsumeClaim(sess sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error { for msg := range claim.Messages() { if hFunc, ok := h.msgHandle[msg.Topic]; ok { hFunc(msg.Value, string(msg.Key)) } sess.MarkMessage(msg, "") } return nil }