9.【go-kit教程】go-kit集成Prometheus

  • 在 Go kit 中集成 Prometheus 进行 API 监控可以帮助开发人员更好地了解系统的性能和行为,提高系统的可观察性和可靠性。下面是一个简单的示例,演示如何在 Go kit 中集成 Prometheus 进行 API 监控:

    package main
    
    import (
            "net/http"
    
            "github.com/go-kit/kit/log"
            "github.com/go-kit/kit/metrics/prometheus"
            "github.com/go-kit/kit/metrics/provider"
            "github.com/go-kit/kit/transport"
            httptransport "github.com/go-kit/kit/transport/http"
            "github.com/prometheus/client_golang/prometheus/promhttp"
    )
    
    func main() {
            // 创建 Prometheus 监控器
            fieldKeys := []string{"method", "error"}
            requestCount := prometheus.NewCounterFrom(provider.NewProvider(), prometheus.CounterOpts{
                    Namespace: "my_api",
                    Name:      "request_count",
                    Help:      "Number of requests received.",
            }, fieldKeys)
            requestLatency := prometheus.NewSummaryFrom(provider.NewProvider(), prometheus.SummaryOpts{
                    Namespace: "my_api",
                    Name:      "request_latency",
                    Help:      "Total duration of requests in microseconds.",
            }, fieldKeys)
    
            // 创建 endpoint
            helloEndpoint := func() string {
                    return "Hello, World!"
            }
            helloEndpoint = transport.NewServer(
                    helloEndpoint,
                    func(ctx context.Context, r *http.Request) (interface{}, error) {
                            return nil, nil
                    },
                    func(ctx context.Context, w http.ResponseWriter, response interface{}) error {
                            w.Header().Set("Content-Type", "text/plain; charset=utf-8")
                            fmt.Fprint(w, response.(string))
                            return nil
                    },
                    transport.ServerErrorLogger(log.NewNopLogger()),
                    transport.ServerErrorEncoder(errorEncoder),
                    transport.ServerBefore(prometheus.HTTPToContext()),
            ).Endpoint()
    
            // 创建 HTTP server
            r := mux.NewRouter()
            r.Handle("/hello", httptransport.NewServer(
                    helloEndpoint,
                    httpDecodeRequest,
                    httpEncodeResponse,
                    httptransport.ServerBefore(prometheus.HTTPToContext()),
                    httptransport.ServerErrorLogger(log.NewNopLogger()),
                    httptransport.ServerErrorEncoder(errorEncoder),
                    httptransport.ServerBefore(prometheus.HTTPToContext()),
            )).Methods("GET")
            r.Handle("/metrics", promhttp.Handler())
    
            fmt.Println("listening on :8080...")
            http.ListenAndServe(":8080", r)
    }
    
    func httpDecodeRequest(_ context.Context, r *http.Request) (interface{}, error) {
            return nil, nil
    }
    
    func httpEncodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error {
            w.Header().Set("Content-Type", "text/plain; charset=utf-8")
            fmt.Fprint(w, response.(string))
            return nil
    }
    
    func errorEncoder(_ context.Context, err error, w http.ResponseWriter) {
            w.Header().Set("Content-Type", "text/plain; charset=utf-8")
            w.WriteHeader(http.StatusBadRequest)
            fmt.Fprint(w, err.Error())
    }