第28关 k8s监控实战之Prometheus(八)

大家好,我是博哥爱运维。从这节课开始,博哥计划引入golang(简称go)语言开发的一些内容,没有接触过go语言的同学也不用慌,我会尽量以一个新人的角度,去把这些go开发的内容讲得通俗一些。这节课还是继续 prometheus监控相关的内容,博哥带大家用go语言开发一个简单的http服务并暴露相应的prometheus指标。

首先电脑上需要安装好go语言,下载链接(选择相应的系统安装包):

https://golang.google.cn/dl/

然后安装好vscode这个编程IDE工具:

https://code.visualstudio.com/

配置好vscode里面go的相关插件,可以参考下这个文档:

https://zhuanlan.zhihu.com/p/320343679

我来先准备写一个简单的http服务扮演我们的业务服务角色

翻译自:https://prometheus.io/docs/tutorials/instrumenting_http_server_in_go/

package main

import (
   "fmt"
   "net/http"
)

func ping(w http.ResponseWriter, req *http.Request){
   fmt.Fprintf(w,"pong")
}

func main() {
   http.HandleFunc("/ping",ping)

   http.ListenAndServe(":8090", nil)
}

运行测试下,确保服务访问正常

然后我们准备创建一个 Prometheus counter计数器,来记录请求数

var pingCounter = prometheus.NewCounter(
   prometheus.CounterOpts{
       Name: "ping_request_count",
       Help: "No of request handled by Ping handler",
   },
)

接着我们在ping函数里面加入 pingCounter.Inc()来引用这个计数器

func ping(w http.ResponseWriter, req *http.Request) {
   pingCounter.Inc()
   fmt.Fprintf(w, "pong")
}

然后将计数器注册到 Default Register 并公开指标

func main() {
   prometheus.MustRegister(pingCounter)
   http.HandleFunc("/ping", ping)
   http.Handle("/metrics", promhttp.Handler())
   http.ListenAndServe(":8090", nil)
}

最终完整代码如下:

package main

import (
   "fmt"
   "net/http"

   "github.com/prometheus/client_golang/prometheus"
   "github.com/prometheus/client_golang/prometheus/promhttp"
)

var pingCounter = prometheus.NewCounter(
   prometheus.CounterOpts{
       Name: "ping_request_count",
       Help: "No of request handled by Ping handler",
   },
)

func ping(w http.ResponseWriter, req *http.Request) {
   pingCounter.Inc()
   fmt.Fprintf(w, "pong")
}

func main() {
   prometheus.MustRegister(pingCounter)

   http.HandleFunc("/ping", ping)
   http.Handle("/metrics", promhttp.Handler())
   http.ListenAndServe(":8090", nil)
}

我们准备来运行它

# 初始化包管理
go mod init prometheus
# 用国内加速代理下载包
export GOPROXY=https://goproxy.cn
# 更新依赖包
go mod tidy
# 运行服务
go run server.go

查看暴露的指标

http://127.0.0.1:8090/metrics

增加一些请求数

http://127.0.0.1:8090/ping

这里我们可以修改prometheus的配置,来监控我们自定义的这个服务,或者也可以参照博哥之前的课程,用serviceMonitor来暴露指标

global:
  scrape_interval: 15s

scrape_configs:
  - job_name: prometheus
    static_configs:
      - targets: ["localhost:9090"]
  - job_name: simple_server
    static_configs:
      - targets: ["localhost:8090"]

你可能感兴趣的:(kubernetes,prometheus,容器,k8s,云原生,vscode,golang)