# 如何配置Go+Grafana+InfluxDB
本文將介紹如何搭建一個完整的監控系統,使用Go語言采集數據,InfluxDB存儲時序數據,并通過Grafana進行可視化展示。
## 一、環境準備
### 1. 安裝InfluxDB
```bash
# Ubuntu/Debian
wget https://dl.influxdata.com/influxdb/releases/influxdb_1.8.10_amd64.deb
sudo dpkg -i influxdb_1.8.10_amd64.deb
sudo systemctl start influxdb
# 驗證安裝
influx -version
# Ubuntu/Debian
sudo apt-get install -y adduser libfontconfig1
wget https://dl.grafana.com/oss/release/grafana_9.5.2_amd64.deb
sudo dpkg -i grafana_9.5.2_amd64.deb
sudo systemctl start grafana-server
influx
> CREATE DATABASE metrics
> CREATE USER grafana WITH PASSWORD 'yourpassword'
> GRANT ALL ON metrics TO grafana
/etc/influxdb/influxdb.conf:[http]
enabled = true
bind-address = ":8086"
go get github.com/influxdata/influxdb1-client/v2
package main
import (
"log"
"time"
influx "github.com/influxdata/influxdb1-client/v2"
)
func writeMetrics() {
c, err := influx.NewHTTPClient(influx.HTTPConfig{
Addr: "http://localhost:8086",
Username: "grafana",
Password: "yourpassword",
})
if err != nil {
log.Fatal(err)
}
defer c.Close()
bp, _ := influx.NewBatchPoints(influx.BatchPointsConfig{
Database: "metrics",
Precision: "s",
})
tags := map[string]string{"host": "server01"}
fields := map[string]interface{}{
"cpu_usage": 42.5,
"mem_usage": 75.3,
}
pt, _ := influx.NewPoint("system_metrics", tags, fields, time.Now())
bp.AddPoint(pt)
if err := c.Write(bp); err != nil {
log.Fatal(err)
}
}
訪問http://localhost:3000(默認admin/admin)
添加數據源:
http://localhost:8086metrics創建Dashboard:
SELECT mean("cpu_usage") FROM "system_metrics" WHERE $timeFilter GROUP BY time($__interval), "host"Go應用 → 寫入數據 → InfluxDB → Grafana可視化
通過以上步驟,您已成功搭建了一個完整的監控系統??梢愿鶕嶋H需求擴展Go程序的指標采集邏輯,并在Grafana中創建更豐富的可視化圖表。 “`
(全文約650字)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。