在日常的 Go 服务开发中,我们常常需要回答几个关键问题:
- 我的服务现在的 QPS(每秒请求数)是多少?
- 服务器的 CPU、内存、磁盘 是否有瓶颈?
- 业务指标和系统指标如何统一暴露?
传统方案是部署 node_exporter + Prometheus,再做一堆配置。但对于小型服务、内网应用、测试环境来说,这种方案太“重”了。
这时,轻量、零依赖的 go-commons 就能派上用场。
它可以帮你在业务应用中快速集成一个 最小可行监控体系(MVP):
👉 业务指标(QPS、接口耗时) + 系统指标(CPU、内存、磁盘) 一步到位。
1. 快速集成 go-commons
首先,拉取依赖:
go get github.com/Rodert/go-commons目录结构(最小 demo):
myapp/
main.go
go.mod2. 代码案例:业务指标 + 系统指标
下面我们写一个简单的 Web 服务,包含两个接口:
-
/hello:模拟业务请求,统计 QPS -
/metrics:暴露业务和系统指标
package main
import (
"encoding/json"
"fmt"
"net/http"
"sync/atomic"
"time"
"github.com/Rodert/go-commons/systemutils/cpuutils"
"github.com/Rodert/go-commons/systemutils/memutils"
"github.com/Rodert/go-commons/systemutils/diskutils"
)
// QPS 计数器
var reqCount uint64
var start = time.Now()
// metrics 输出结构
type Metrics struct {
QPS float64 `json:"qps"`
CPUUsage float64 `json:"cpu_usage"`
LoadAvg []float64 `json:"load_avg"`
MemUsedMB uint64 `json:"mem_used_mb"`
MemTotalMB uint64 `json:"mem_total_mb"`
DiskUsedGB uint64 `json:"disk_used_gb"`
DiskTotalGB uint64 `json:"disk_total_gb"`
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
atomic.AddUint64(&reqCount, 1)
fmt.Fprintln(w, "Hello, World!")
}
func metricsHandler(w http.ResponseWriter, r *http.Request) {
// 计算 QPS
duration := time.Since(start).Seconds()
qps := float64(atomic.LoadUint64(&reqCount)) / duration
m := Metrics{QPS: qps}
// CPU
if cpuInfo, err := cpuutils.GetCPUInfo(); err == nil {
m.CPUUsage = cpuInfo.UsagePercent
m.LoadAvg = cpuInfo.LoadAvg
}
// 内存
if memInfo, err := memutils.GetMemInfo(); err == nil {
m.MemUsedMB = memInfo.Used / 1024 / 1024
m.MemTotalMB = memInfo.Total / 1024 / 1024
}
// 磁盘
if diskInfo, err := diskutils.GetDiskInfo("/"); err == nil {
m.DiskUsedGB = diskInfo.Used / 1024 / 1024 / 1024
m.DiskTotalGB = diskInfo.Total / 1024 / 1024 / 1024
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(m)
}
func main() {
http.HandleFunc("/hello", helloHandler)
http.HandleFunc("/metrics", metricsHandler)
fmt.Println("Server started at :8080")
http.ListenAndServe(":8080", nil)
}3. 实际效果
启动服务:
go run main.go访问业务接口几次:
curl http://localhost:8080/hello查看监控指标:
curl http://localhost:8080/metrics输出示例:
{
"qps": 12.5,
"cpu_usage": 8.34,
"load_avg": [0.12, 0.20, 0.30],
"mem_used_mb": 512,
"mem_total_mb": 4096,
"disk_used_gb": 20,
"disk_total_gb": 100
}这就是一套 最小可行监控体系。
4. 为什么选择 go-commons?
- 零依赖:只用标准库 + go-commons,避免引入庞大依赖。
- 跨平台:Linux、macOS、Windows 都支持。
- 即插即用:无需额外部署 node_exporter。
- 轻量:非常适合小型服务、测试环境、嵌入式应用。
5. 一起完善 go-commons 🚀
目前 go-commons 已支持 CPU、内存、磁盘 三大核心指标,未来计划:
- 增加 网络流量、goroutine 数量、GC 次数
- 更紧密的 Prometheus exporter 集成
- 提供更多 监控模板示例
👉 项目地址:https://github.com/Rodert/go-commons
如果你也希望 每个 Go 服务都能自带健康监控,欢迎试用,并参与贡献!
















