当前位置: 首页> 健康> 母婴 > 10.3 查看源码,讲解采集原理

10.3 查看源码,讲解采集原理

时间:2025/8/8 1:19:18来源:https://blog.csdn.net/weixin_48502062/article/details/141105499 浏览次数:0次

本节重点介绍 :

  • redis-exporter源码解读

源码解读

初始化redis-exporter对象

  • 代码位置 D:\go_path\pkg\mod\github.com\oliver006\redis_exporter@v1.24.0\main.go
exp, err := exporter.NewRedisExporter()

NewRedisExporter中注册 /scrape handler

  • 位置 D:\go_path\pkg\mod\github.com\oliver006\redis_exporter@v1.24.0\exporter\exporter.go
e.mux.HandleFunc("/scrape", e.scrapeHandler)

scrapeHandler 注册采集对象

  • 位置 D:\go_path\pkg\mod\github.com\oliver006\redis_exporter@v1.24.0\exporter\http.go
  • 解析target参数
  • 创建RedisExporter
  • 注册采集对象
    target := r.URL.Query().Get("target")_, err = NewRedisExporter(target, opts)if err != nil {http.Error(w, "NewRedisExporter() err: err", http.StatusBadRequest)e.targetScrapeRequestErrors.Inc()return}promhttp.HandlerFor(registry, promhttp.HandlerOpts{ErrorHandling: promhttp.ContinueOnError},

执行采集

  • 调用 RedisExporter绑定的Collect方法
  • e.scrapeRedisHost(ch) 代表连接redis实例执行采集
// Collect fetches new metrics from the RedisHost and updates the appropriate metrics.
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {e.Lock()defer e.Unlock()e.totalScrapes.Inc()if e.redisAddr != "" {startTime := time.Now()var up float64if err := e.scrapeRedisHost(ch); err != nil {e.registerConstMetricGauge(ch, "exporter_last_scrape_error", 1.0, fmt.Sprintf("%s", err))} else {up = 1e.registerConstMetricGauge(ch, "exporter_last_scrape_error", 0, "")}e.registerConstMetricGauge(ch, "up", up)took := time.Since(startTime).Seconds()e.scrapeDuration.Observe(took)e.registerConstMetricGauge(ch, "exporter_last_scrape_duration_seconds", took)}ch <- e.totalScrapesch <- e.scrapeDurationch <- e.targetScrapeRequestErrors
}

最终的执行函数 scrapeRedisHost

  • 连接redis获得 client对象c,对应的redis库 为 github.com/gomodule/redigo/redis
c, err := e.connectToRedis()
  • 调用封装好的 doRedisCmd函数执行redis 命令
func doRedisCmd(c redis.Conn, cmd string, args ...interface{}) (interface{}, error) {log.Debugf("c.Do() - running command: %s %s", cmd, args)res, err := c.Do(cmd, args...)if err != nil {log.Debugf("c.Do() - err: %s", err)}log.Debugf("c.Do() - done")return res, err
}
  • 执行redis命令 ,做结果转换,推送到ch中即可

本节重点总结 :

  • redis-exporter源码解读
关键字:10.3 查看源码,讲解采集原理

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: