昨天写了有关自己开源的一个go-gateway的文章, 在文章中提到了使用fasthttp完全替代了原生的net/http,
在gateway的项目中,提供通过grafana+prometheus来进行gateway整体调度的动态状态监控,在GPE的监控体系中,exporter是个必不可少的组件, 以前的springcloud的gateway中,是使用的 spring cloud集成的prometheus-client, 现在功能迁移到golang里,当然也要有golang的prometheus, prometheus官方提供了golang的支持,可惜是在net/http下的,可以看看prometheus的代码包,里面的prometheushttp包里,提供了net/http的支持,但是我们使用的fasthttp作为gateway的底层通信,当然完全可以单独在开一个无关的端口,通过net/http来提供prometheus的功能, 不过想着浪费资源了,在docker和k8s里,还要expose一个无关的端口,就没有这样做。
自己在prometheus的基础上,简单的进行一些fasthttp的封装, github的项目地址 GitHub – gohutool/boot4go-prometheus: a prometheus exporter support for fasthttp
简单使用
添加引用
import (
prometheusfasthttp "github.com/gohutool/boot4go-prometheus/fasthttp"
)
Add PrometheusHandler and map the metrics path
handler := func(ctx *fasthttp. request Ctx) {
switch string(ctx.Path()) {
case "/metrics":
prometheusfasthttp.PrometheusHandler(prometheusfasthttp.HandlerOpts{})(ctx)
case "/sample1":
sample1HandlerFunc(ctx)
case "/sample2":
sample2HandlerFunc(ctx)
default:
ctx.Error("not found", fasthttp.StatusNotFound)
}
}
fasthttp.ListenAndServe(":80", handler)
或者
handler := prometheusfasthttp.PrometheusHandlerFor(prometheusfasthttp.HandlerOpts{}, func(ctx *fasthttp.RequestCtx) {
switch string(ctx.Path()) {
case "/metrics":
return
case "/sample1":
sample1HandlerFunc(ctx)
case "/sample2":
sample2HandlerFunc(ctx)
default:
ctx.Error("not found", fasthttp.StatusNotFound)
}
})
fasthttp.ListenAndServe(":80", handler)
如果使用的是第三方的 Router 产品,比如fasthttp-router
func InitRouter(router *routing.Router) {
router.Get("/metrics", func(context *routing.Context) error {
prometheusfasthttp.PrometheusHandler(prometheusfasthttp.HandlerOpts{})(context.RequestCtx)
return nil
})
}
添加自己的监控指标
prometheus.MustRegister(totalCounterVec)
prometheus.MustRegister(amountSummaryVec)
prometheus.MustRegister(amountGaugeVec)
添加默认的请求状况的metrics 统计指标
requestHandler := func(ctx *fasthttp.RequestCtx) {
Logger.Debug("%v %v %v %v", string(ctx.Path()), ctx.URI().String(), string(ctx.Method()), ctx.QueryArgs().String())
defer func() {
if err := recover(); err != nil {
Logger.Debug(err)
// ctx.Error(fmt.Sprintf("%v", err), http.StatusInternalServerError)
Error(ctx, Result.Fail(fmt.Sprintf("%v", err)). Json (), http.StatusInternalServerError)
}
ctx.Response. Header .Set("tick", time.Now().String())
ctx.Response.Header.SetServer("Gateway-UIManager")
prometheusfasthttp.RequestCounterHandler(nil)(ctx)
Logger.Debug("router.HandleRequest is finish")
}()
router.HandleRequest(ctx)
}
// Start HTTP server.
Logger.Info("Starting HTTP server on %v", listener.Addr().String())
go func() {
if err := fasthttp.Serve(listener, requestHandler); err != nil {
Logger.Critical("error in ListenAndServe: %v", err)
}
}()
通过访问 metrics, 查看指标结果

搞定, 套接上grafana + prometheus, 就可以通过仪表盘来查看gateway的调用情况了。
真香