流量回放工具之 GoReplay output-http-stats(HTTP请求统计) 源码分析

x33g5p2x  于2021-10-26 转载在 Go  
字(2.0k)|赞(0)|评价(0)|浏览(635)

前言

GoReplay 可以报告 stats 请求队列的统计信息。通过结合使用--output-http-stats和选项,默认统计信息每 5 秒输出到给控制台。

参数:–stats --output-http-stats

  1. -output-http-stats //每5秒钟输出一次输出队列的状态
  2. Report http output queue stats to console every N milliseconds. See output-http-stats-ms
  3. -output-http-stats-ms int
  4. Report http output queue stats to console every N milliseconds. default: 5000 (default 5000)

控制台输出是这样的:

其中倒数第二列等同于当前的TPS;

output_http.go

HTTPOutputConfig 统计信息收集
是否收集统计信息,统计输出间隔是多少

  1. if o.config.Stats {
  2. o.queueStats = NewGorStat("output_http", o.config.StatsMs)
  3. }

统计信息收集:

  1. // PluginWrite writes message to this plugin
  2. // 统计信息收集
  3. func (o *HTTPOutput) PluginWrite(msg *Message) (n int, err error) {
  4. if !isRequestPayload(msg.Meta) {
  5. return len(msg.Data), nil
  6. }
  7. select {
  8. case <-o.stop:
  9. return 0, ErrorStopped
  10. case o.queue <- msg:
  11. }
  12. if o.config.Stats {
  13. o.queueStats.Write(len(o.queue))
  14. }
  15. if len(o.queue) > 0 {
  16. // try to start a new worker to serve
  17. if atomic.LoadInt32(&o.activeWorkers) < int32(o.config.WorkersMax) {
  18. go o.startWorker()
  19. atomic.AddInt32(&o.activeWorkers, 1)
  20. }
  21. }
  22. return len(msg.Data) + len(msg.Meta), nil
  23. }

gor_stat.go

NewGorStat 统计类:

  1. // NewGorStat统计类
  2. func NewGorStat(statName string, rateMs int) (s *GorStat) {
  3. s = new(GorStat)
  4. s.statName = statName
  5. s.rateMs = rateMs
  6. s.latest = 0
  7. s.mean = 0
  8. s.max = 0
  9. s.count = 0
  10. if Settings.Stats {
  11. go s.reportStats()
  12. }
  13. return
  14. }

写入时做统计:

  1. //写入时做统计
  2. func (s *GorStat) Write(latest int) {
  3. if Settings.Stats {
  4. if latest > s.max {
  5. s.max = latest
  6. }
  7. if latest != 0 {
  8. s.mean = ((s.mean * s.count) + latest) / (s.count + 1)
  9. }
  10. s.latest = latest
  11. s.count = s.count + 1
  12. }
  13. }

打印输出,简单的sleep:

  1. //打印输出,简单的sleep
  2. func (s *GorStat) reportStats() {
  3. Debug(0, "\n", s.statName+":latest,mean,max,count,count/second,gcount")
  4. for {
  5. Debug(0, "\n", s)
  6. s.Reset()
  7. time.Sleep(time.Duration(s.rateMs) * time.Millisecond)
  8. }

字符串类型强转:

  1. //字符串类型转换
  2. func (s *GorStat) String() string {
  3. return s.statName + ":" + strconv.Itoa(s.latest) + "," + strconv.Itoa(s.mean) + "," + strconv.Itoa(s.max) + "," + strconv.Itoa(s.count) + "," + strconv.Itoa(s.count/(s.rateMs/1000.0)) + "," + strconv.Itoa(runtime.NumGoroutine())
  4. }

runtime.NumGoroutine():返回当前存在的协程的数量。

核心调用逻辑图

相关文章

最新文章

更多