我有几个 url 可以访问,我想用 prometheus 监控每个请求的成本时间。
但我不知道使用哪种指标来收集数据。有什么帮助吗?
这是演示代码:
package main
import (
"github.com/prometheus/client_golang/prometheus"
"io/ioutil"
"net/http"
"fmt"
"time"
)
var (
resTime = prometheus.NewSummaryVec(
prometheus.SummaryOpts{
Name: "response_time",
Help: "cost time per request",
},
[]string{"costTime"},
)
)
func main() {
urls := []string{"http://www.google.com","http://www.google.com"}
for _,url := range urls {
request(url)
}
}
func request(url string){
startTime := time.Now()
response,_ := http.Get(url)
defer response.Body.Close()
_,err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(err)
}
costTime := time.Since(startTime)
resTime.WithLabelValues(fmt.Sprintf("%d", costTime)).Observe(costTime.Seconds())
}
最佳答案
Prometheus 建议您使用 histogram存储这样的东西。它本质上是根据它属于哪个时间“桶”来计算请求。在 godoc 中有一个如何使用它的示例.
我更喜欢直方图而不是“摘要”类型,因为当您有很多服务器在玩时,它更容易聚合。如果您只保留每台服务器上的平均/第 99 个百分位时间,则很难仅从该信息中了解全局平均值。
直方图保持每个服务器每个桶的运行计数,因此您可以跨服务器聚合数据,而不会在未来造成重大损失。
在 this page 上可以找到这些类型的一个很好的概述。 .
关于go - 如何在 golang 网络服务器中使用 prometheus 监控请求成本时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45918567/