1. 使用pprof进行深度性能分析
pprof是Go语言内置的性能分析工具,支持CPU、内存、Goroutine、阻塞操作(Block)、互斥锁(Mutex)等多维度分析,是Golang性能调优的核心工具。
net/http/pprof包(无需修改业务代码即可暴露分析接口),并启动一个HTTP服务器(通常监听localhost:6060)。示例代码:import (
"log"
"net/http"
_ "net/http/pprof" // 自动注册pprof处理器
)
func main() {
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil)) // 后台运行pprof服务
}()
// 你的应用逻辑
}
http://localhost:6060/debug/pprof/查看所有可用的分析端点(如profile(CPU)、heap(内存)、goroutine(协程))。go tool pprof收集数据并生成可视化报告。例如,收集30秒CPU数据并进入交互式shell:go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
生成内存分配火焰图(需安装graphviz):go tool pprof -http=:8080 http://localhost:6060/debug/pprof/heap
2. 集成Prometheus+Grafana实现实时监控与可视化
Prometheus是开源时间序列数据库,Grafana是可视化工具,二者结合可实现对Golang应用的全方位监控(如请求量、延迟、错误率、资源使用率)。
wget https://github.com/prometheus/prometheus/releases/download/v2.36.1/prometheus-2.36.1.linux-amd64.tar.gz
tar xvfz prometheus-2.36.1.linux-amd64.tar.gz
cd prometheus-2.36.1.linux-amd64
./prometheus --config.file=prometheus.yml # 默认监听9090端口
sudo yum install -y grafana
sudo systemctl start grafana-server
sudo systemctl enable grafana-server
prometheus.yml,添加Golang应用的监控目标(假设应用暴露/metrics接口在8080端口):scrape_configs:
- job_name: 'go_app'
static_configs:
- targets: ['localhost:8080']
prometheus/client_golang库暴露自定义指标(如HTTP请求延迟、业务计数器)。示例代码:import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
httpRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests",
},
[]string{"method", "path"}, // 标签:HTTP方法、路径
)
requestDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "Duration of HTTP requests in seconds",
Buckets: prometheus.DefBuckets, // 默认桶(0.005s、0.01s、0.025s等)
},
[]string{"method", "path"},
)
)
func init() {
prometheus.MustRegister(httpRequestsTotal)
prometheus.MustRegister(requestDuration)
}
func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
duration := time.Since(start).Seconds()
// 记录指标
httpRequestsTotal.WithLabelValues(r.Method, r.URL.Path).Inc()
requestDuration.WithLabelValues(r.Method, r.URL.Path).Observe(duration)
})
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World"))
})
// 使用中间件包装路由
wrappedMux := middleware(mux)
// 暴露Prometheus指标接口
http.Handle("/metrics", promhttp.Handler())
// 启动服务
go func() {
log.Println(http.ListenAndServe("localhost:8080", wrappedMux))
}()
// 你的应用逻辑
}
http://localhost:3000,默认账号admin/admin),添加Prometheus作为数据源,然后导入Golang监控仪表板(如ID:2583,包含请求量、延迟、错误率等面板),即可实时查看应用性能趋势。3. 使用expvar暴露基础运行时指标
expvar是Go标准库中的包,可自动暴露应用的基础运行时指标(如内存使用量、GC次数、协程数量),无需额外依赖,适合快速查看应用状态。
expvar包,并注册自定义指标(可选)。示例代码:import (
"expvar"
"net/http"
)
var (
numRequests = expvar.NewInt("num_requests") // 自定义计数器
)
func main() {
http.Handle("/metrics", expvar.Handler()) // 暴露指标接口
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
numRequests.Add(1) // 记录请求数
w.Write([]byte("Hello, expvar"))
})
log.Println(http.ListenAndServe("localhost:8080", nil))
}
http://localhost:8080/debug/vars,返回JSON格式的指标数据(包含内存分配、GC次数、协程数量等)。也可通过expvar.Handler()将指标暴露为HTTP接口,方便与Zabbix、Munin等传统监控系统集成。4. 利用OpenTelemetry实现全链路追踪
OpenTelemetry是开源观测性框架,支持分布式追踪、指标收集、日志管理,适合微服务架构下的Golang应用性能监控。
go get go.opentelemetry.io/otel
go get go.opentelemetry.io/otel/trace
go get go.opentelemetry.io/otel/sdk
import (
"context"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
"net/http"
)
func main() {
tracer := otel.Tracer("go-app") // 创建Tracer
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
ctx, span := tracer.Start(r.Context(), "handle_request") // 开始Span
defer span.End() // 结束Span
// 业务逻辑
w.Write([]byte("Hello, OpenTelemetry"))
})
log.Println(http.ListenAndServe("localhost:8080", nil))
}
5. 使用系统级工具补充监控
除了应用层工具,还可使用CentOS系统级工具监控Golang应用的资源使用情况(如CPU、内存、磁盘、网络),适合排查基础设施层面的性能问题。
top/htop:实时查看进程的CPU、内存占用(htop需安装:sudo yum install -y htop)。vmstat:查看系统整体资源使用情况(如CPU、内存、IO):vmstat 1 5 # 每1秒刷新一次,共5次
iostat:查看磁盘IO性能(需安装sysstat包):iostat -x 1 5
netstat/ss:查看网络连接状态(如TCP连接数、端口占用):netstat -tulnp | grep go_app