在日常 Go 服務開發中,我們通常需要同時監控 業務指標(比如 QPS、請求延遲、錯誤率),也需要關注 系統指標(CPU、內存、磁盤占用情況)。
過去這類場景通常要引入多個庫:一個負責業務指標采集(Prometheus client),另一個負責系統指標采集(比如 node_exporter 或 gopsutil)。
現在有一個新的開源項目 —— go-commons,它內置了 CPU / 內存 / 磁盤的采集工具,并且提供了豐富的字符串、并發、集合操作工具,可以讓我們更快地把 系統監控和業務監控結合起來。
這篇文章就帶大家寫一個最小化的 Web 服務:
👉 使用 go-commons
獲取系統資源指標
👉 同時統計 Web 服務的 QPS
👉 最終暴露 /metrics
接口,交給 Prometheus 采集
場景描寫:為什么需要應用+系統雙指標?
想象一下,你上線了一個 Go Web 服務,結果突然響應變慢。
你打開監控系統:
- 看到 QPS 正常,但是 平均響應時間升高
- 系統監控發現 內存使用率拉滿
- 最后定位是某個業務邏輯有內存泄漏
如果你的應用里沒有同時暴露業務指標和系統指標,可能要對接多個監控面板來排查。
而現在我們用 go-commons + Prometheus,一站式搞定。
代碼實現
下面我們實現一個最小的 Web 服務:
/hello
:業務 API,用來模擬請求/metrics
:暴露 Prometheus 指標,包括 QPS + 內存使用率
package mainimport ("fmt""net/http""sync/atomic""time""github.com/Rodert/go-commons/systemutils/memutils""github.com/prometheus/client_golang/prometheus""github.com/prometheus/client_golang/prometheus/promhttp"
)var (// 定義業務指標:QPSrequestsTotal = prometheus.NewCounter(prometheus.CounterOpts{Name: "app_requests_total",Help: "Total number of requests handled by the app",},)// 定義系統指標:內存使用率memUsageGauge = prometheus.NewGauge(prometheus.GaugeOpts{Name: "system_memory_usage_percent",Help: "Memory usage percentage from go-commons",},)// 并發安全計數器activeRequests int64
)func init() {// 注冊 Prometheus 指標prometheus.MustRegister(requestsTotal)prometheus.MustRegister(memUsageGauge)
}// 模擬業務接口
func helloHandler(w http.ResponseWriter, r *http.Request) {atomic.AddInt64(&activeRequests, 1)defer atomic.AddInt64(&activeRequests, -1)requestsTotal.Inc() // 請求數 +1fmt.Fprintf(w, "Hello, world! Active Requests: %d\n", atomic.LoadInt64(&activeRequests))
}// 定時采集內存使用率
func startMemCollector() {go func() {for {memInfo, err := memutils.GetMemInfo()if err == nil && memInfo.Total > 0 {usage := float64(memInfo.Used) / float64(memInfo.Total) * 100memUsageGauge.Set(usage)}time.Sleep(5 * time.Second)}}()
}func main() {startMemCollector()http.HandleFunc("/hello", helloHandler)http.Handle("/metrics", promhttp.Handler())fmt.Println("🚀 Server started at :8080")http.ListenAndServe(":8080", nil)
}
運行服務后:
go run main.go
訪問接口:
-
http://localhost:8080/hello
👉 模擬業務請求 -
http://localhost:8080/metrics
👉 可以看到 Prometheus 指標,包括:
# HELP app_requests_total Total number of requests handled by the app
# TYPE app_requests_total counter
app_requests_total 3# HELP system_memory_usage_percent Memory usage percentage from go-commons
# TYPE system_memory_usage_percent gauge
system_memory_usage_percent 45.8
現在你就擁有了 應用+系統雙指標 的監控能力 🚀。
為什么選擇 go-commons?
相比直接使用 gopsutil 或者 node_exporter:
- go-commons 更輕量,依賴更少,大部分功能基于標準庫實現
- 內置了 字符串、集合、并發工具,不僅能采集系統指標,還能在業務邏輯里更快寫工具函數
- 提供了 本地/在線 API 文檔(點擊查看),開發體驗更友好
一句話:它不僅是工具庫,還能成為你寫監控采集器的“底座”。
邀請大家參與開源 🎉
go-commons 目前還在快速迭代中:
- 我們計劃增強 systemutils,提供更多監控指標(網絡、進程、IO 等)
- 歡迎大家提交 PR,貢獻新的工具函數或監控擴展
- 也歡迎在 Issue 里分享你的使用場景,讓這個項目更貼近開發者的需求
開源的意義不僅在于“拿來用”,更在于一起打磨。
如果你也對 Go 工具庫 + 監控場景 感興趣,快來加入吧!
👉 項目地址:https://github.com/Rodert/go-commons