腾讯mini项目-【指标监控服务重构】2023-08-19

今日已办

benchmark

How can we create a configuration for gobench with -benchmem -- IDEs Support (IntelliJ Platform) | JetBrains

本机进行watermill-benchmark

  1. 使用 apifox 自动化测试上报固定数量的消息

  2. 启动watermill-pub/sub的 benchmark 函数

    go 复制代码
    func BenchmarkPubSub(b *testing.B) {
    	for i := 0; i < 1; i++ {
    		b.StopTimer()
    		logger := watermillzap.NewLogger(log.Logger)
    		publisher, subscriber := consumer.NewPubSub(logger)
    		router, err := message.NewRouter(message.RouterConfig{}, logger)
    		if err != nil {
    			log.Logger.Fatal("create router error", zap.Error(err))
    		}
    
    		router.AddPlugin(plugin.SignalsHandler)
    		router.AddMiddleware(
    			middleware.InstantAck,
    			middleware.Recoverer,
    		)
    
    		router.AddMiddleware(consumer.UnpackKafkaMessage, consumer.InitPerformanceEvent, consumer.AnalyzeEvent)
    		router.AddHandler("crash", "to_analyzer__0.PERF_CRASH", subscriber, "solar-dev.PERF_CRASH", publisher, consumer.CrashHandler)
    		router.AddHandler("lag", "to_analyzer__0.PERF_LAG", subscriber, "solar-dev.PERF_LAG", publisher, consumer.LagHandler)
    		go func() {
    			for {
    				if kafka.PublishCount >= 10000 && router.IsRunning() {
    					err = router.Close()
    					fmt.Printf("router close err:%v\n", err)
    					break
    				}
    			}
    		}()
    		b.StartTimer()
    		if err = router.Run(context.Background()); err != nil {
    			log.Logger.Error("router run error", zap.Error(err))
    		}
    	}
    }

单 topic

Event number ms ns/op B/op allocs/op
crash 10 698 0.01306 0 0
crash 100 701 0.01373 0 0
crash 1000 1143 1164375900 131129392 815484
crash 10000 6174 6160307300 1300089088 8179332

双 topic

Event number ms ns/op B/op allocs/op
crash & lag 10 689 0.01486 0 0
crash & lag 100 718 0.01438 0 0
crash & lag 1000 1661 1677269200 269949888 1797754
crash & lag 10000 11697 11573685900 2684430704 17945041

add publisher send message trace & log logic

  1. 在 handler 了中将 data 用 message 的 Context 传递下来
  2. 获取 WriteKafkaSpan 和 RootSpan 手动 End
  3. 打日志

profile/internal/watermill/pubsub/consumer_stage.go

go 复制代码
// crashHandler
// @Description
// @Author xzx 2023-08-12 15:09:15
// @Param msg
// @Return []*message.Message
// @Return error
func crashHandler(msg *message.Message) ([]*message.Message, error) {
	data := GetDataFromMsg(msg)

	writeKafkaCtx, span := otelclient.ConsumerTracer.Start(data.RootSpanCtx, "crashHandler",
		trace.WithSpanKind(trace.SpanKindProducer))
	setSpanAttributes(span, data)
	data.WriteKafkaSpan = span
	toWriteBytes, contextErr := json.Marshal(data.Event)
	if contextErr != nil {
		data.Status = state.StatusUnmarshalError
		handlerErr(writeKafkaCtx, "marshal error", contextErr)
		data.WriteKafkaSpan.End()
		data.RootSpan.End()
		return nil, contextErr
	}

	msg = message.NewMessage(data.Event.BackendID, toWriteBytes)
	msg.Metadata.Set(watermillkafka.HeaderKey, data.Event.ID)
	log.Logger.Info("[4-crashHandler]", zap.String("topic", connector.GetTopic(data.Event.Category)), zap.String("id", data.Event.ID), zap.String("msg", string(toWriteBytes)))

	SetDataInMsg(msg, data)
	return message.Messages{msg}, nil
}

profile/internal/watermill/watermillkafka/publisher.go

go 复制代码
// Publish publishes message to Kafka.
//
// Publish is blocking and wait for ack from Kafka.
// When one of messages delivery fails - function is interrupted.
func (p *Publisher) Publish(topic string, msgs ...*message.Message) error {
	if p.closed {
		return errors.New("publisher closed")
	}

	logFields := make(watermill.LogFields, 4)
	logFields["topic"] = topic

	for _, msg := range msgs {
		logFields["message_uuid"] = msg.UUID
		p.logger.Trace("Sending message to Kafka", logFields)

		kafkaMsg, err := p.config.Marshaler.Marshal(topic, msg)
		if err != nil {
			return errors.Wrapf(err, "cannot marshal message %s", msg.UUID)
		}

		// todo: add otel-trace and log about sendMessage
		data := pubsub.GetDataFromMsg(msg)
		partition, offset, err := p.producer.SendMessage(kafkaMsg)
		if err != nil {
			log.Logger.ErrorContext(msg.Context(), "send message to kafka error", zap.Error(err))
			data.WriteKafkaSpan.End()
			data.RootSpan.End()
			return errors.Wrapf(err, "cannot produce message %s", msg.UUID)
		}
		log.Logger.Info("[4-WriteKafka] write kafka success",
			zap.String("topic", connector.GetTopic(data.Event.Category)),
			zap.String("id", data.Event.ID), zap.Any("msg", data.Event),
			zap.String("profile_root_span_id", data.RootSpan.SpanContext().SpanID().String()))

		data.WriteKafkaSpan.End()
		logFields["kafka_partition"] = partition
		logFields["kafka_partition_offset"] = offset

		p.logger.Trace("Message sent to Kafka", logFields)
		data.RootSpan.End()
	}

	return nil
}

明日待办

  1. ppt 制作
相关推荐
雷电云手机3 小时前
重构阿塔提斯新手玩法攻略 重构阿塔提斯新手英雄推荐
重构
科研工作站4 小时前
【多时段】含sop的配电网重构【含分布式电源】【已更新视频讲解】
重构·配电网·二阶锥·分布式电源·33节点·多时段
天天进步20154 小时前
Vue项目重构实践:如何构建可维护的企业级应用
前端·vue.js·重构
H1004 小时前
重构(二)
android·重构
慕城南风13 小时前
Go语言中的defer,panic,recover 与错误处理
golang·go
fusugongzi18 小时前
clickhouse复现&修复 结构需要清理 错误 structure need clean
clickhouse
山高终有顶,人行无尽头18 小时前
clickhouse查询使用order by和limit,不同limit查询出现重复数据问题【已解决】
clickhouse
桃园码工2 天前
1-Gin介绍与环境搭建 --[Gin 框架入门精讲与实战案例]
go·gin·环境搭建
云中谷2 天前
Golang 神器!go-decorator 一行注释搞定装饰器,v0.22版本发布
go·敏捷开发
苏三有春2 天前
五分钟学会如何在GitHub上自动化部署个人博客(hugo框架 + stack主题)
git·go·github