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

------> 课程视频同步分享在今日头条B站

大家好,我是博哥爱运维。从这节课开始,博哥计划引入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"]
  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值