1. 为 HTTPServer 添加 0-2 秒的随机延时;
2. 为 HTTPServer 项目添加延时 Metric;
3. 将 HTTPServer 部署至测试集群,并完成 Prometheus 配置;
4. 从 Promethus 界面中查询延时指标数据;
5. (可选)创建一个 Grafana Dashboard 展现延时分配情况。
1. 为 HTTPServer 添加 0-2 秒的随机延时
添加 controller
package controller import ( "fmt" "httpserver/utils/metrics" "math/rand" "net/http" "time" ) func registerImagesRoutes() { http.HandleFunc("/images", handleImages) } // 添加 0-2 秒的随机延时 func handleImages(w http.ResponseWriter, r *http.Request) { timer := metrics.NewTimer() defer timer.ObserveTotal() randInt := rand.Intn(2000) time.Sleep(time.Millisecond * time.Duration(randInt)) w.Write([]byte(fmt.Sprintf("<h1>%d<h1>", randInt))) }
注册路由
package controller // RegisterRoutes ... func RegisterRoutes() { registerImagesRoutes() }
运行测试
curl curl http://localhost:8888/images
多请求几次,会输出不同的延迟数
<h1>81<h1> <h1>1887<h1> <h1>59<h1>
2. 为 HTTPServer 项目添加延时 Metric
自定义 metrics,参考自 https://github.com/kubernetes/autoscaler/blob/master/vertical-pod-autoscaler/pkg/utils/metrics/metrics.go
package metrics import ( "fmt" "github.com/prometheus/client_golang/prometheus" "time" ) func Register() { err := prometheus.Register(functionLatency) if err != nil { fmt.Println(err) } } const ( MetricsNamespace = "cloudnative" ) func NewTimer() *ExecutionTimer { return NewExecutionTimer(functionLatency) } var ( functionLatency = CreateExecutionTimeMetric(MetricsNamespace, "Time spent.") ) func NewExecutionTimer(histo *prometheus.HistogramVec) *ExecutionTimer { now := time.Now() return &ExecutionTimer{histo: histo, start: now, last: now} } func (t *ExecutionTimer) ObserveTotal() { (*t.histo).WithLabelValues("total").Observe(time.Now().Sub(t.start).Seconds()) } func CreateExecutionTimeMetric(namespace string, help string) *prometheus.HistogramVec { return prometheus.NewHistogramVec( prometheus.HistogramOpts{ Namespace: namespace, Name: "execution_latency_seconds", Help: help, Buckets: prometheus.ExponentialBuckets(0.001, 2, 15), }, []string{"step"}, ) } type ExecutionTimer struct { histo *prometheus.HistogramVec start time.Time last time.Time }
添加路由处理
package controller import ( "github.com/prometheus/client_golang/prometheus/promhttp" "net/http" ) func registerMetricsRoutes() { http.Handle("/metrics", promhttp.Handler()) }
注册路由
package controller // RegisterRoutes ... func RegisterRoutes() { registerMetricsRoutes() }
测试
参考文档
3. 将 HTTPServer 部署至测试集群,并完成 Prometheus 配置
部署出现 error
go: github.com/prometheus/client_golang@v1.12.1: Get "https://goproxy.cn/github.com/prometheus/client_golang/@v/v1.12.1.mod": dial tcp 180.97.64.41:443: i/o timeout
指定网络重新构建
docker build --network host -f Dockerfile -t httpserver:0.10.1 .
修改 httpserver.yaml 文件的镜像版本号,重新应用
kubectl apply -f httpserver.yaml
4. 从 Promethus 界面中查询延时指标数据