gRPC is a RPC framework based on HTTP and is frequently used for communications among micro service inside the same organization network. However, the service functions cannot be accessed via normal HTTP URL as it's not a WEB framework. In this case, how to do pprof on a gRPC service?
The trick is starting a HTTP server asynchronously while starting the gRPC service. This HTTP server can be accessed to run prrof debug.
go func(){
http.ListenAndServe(":10001", nil)
}()
Since it uses the default ServerMux
, the pprof related routes will be registered automatically after importing the package net/http/pprof
.
import _ "net/http/pprof"
If you are using customized ServerMux, can register below routes in your code.
r.HandleFunc("/debug/pprof/", pprof.Index)
r.HandleFunc("/debug/pprof/heap", pprof.Index)
r.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
r.HandleFunc("/debug/pprof/profile", pprof.Profile)
r.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
r.HandleFunc("/debug/pprof/trace", pprof.Trace)
The complete code logic structure looks like:
func main () {
go func() {
http.ListenAndServe(":10001", nil)
}()
lis, err := net.Listen("tcp", 10000)
grpcServer := grpc.NewServer()
pb.RegisterRouteGuideServer(grpcServer, &routeGuideServer{})
grpcServer.Serve(lis)
}
Now once the service is started, can access {server_ip}:10001/debug/pprof/profile
to trigger pprof generation.
With this, you can check CPU usage and other metrics.
Reference: Golang程åºæ€§èƒ½åˆ†æžï¼ˆä¸‰ï¼‰ç”¨pprof分æžgRPCæœåŠ¡çš„性能 (qq.com)