package main
import (
"fmt"
"os"
"time"
"github.com/influxdata/influxdb1-client/v2"
)
func main() {
// 连接InfluxDB
c, err := client.NewHTTPClient(client.HTTPConfig{
Addr: "http://localhost:8086",
})
if err != nil {
fmt.Println("Error creating InfluxDB client: ", err.Error())
os.Exit(1)
}
defer c.Close()
// 创建InfluxDB数据库
_, err = queryDB(c, "CREATE DATABASE mydb")
if err != nil {
fmt.Println("Error creating database: ", err.Error())
os.Exit(1)
}
// 保存CPU使用率数据
for {
cpuUsage := getCPULoad() // 获取CPU使用率的自定义函数
pt, err := client.NewPoint(
"cpu_usage",
map[string]string{},
map[string]interface{}{"value": cpuUsage},
time.Now(),
)
if err != nil {
fmt.Println("Error creating data point: ", err.Error())
continue
}
bp, err := client.NewBatchPoints(client.BatchPointsConfig{
Database: "mydb",
Precision: "s",
})
if err != nil {
fmt.Println("Error creating batch points: ", err.Error())
continue
}
bp.AddPoint(pt)
// 写入数据到InfluxDB
if err := c.Write(bp); err != nil {
fmt.Println("Error writing to InfluxDB: ", err.Error())
}
time.Sleep(time.Second * 5) // 每5秒记录一次数据
}
}
func getCPULoad() float64 {
// 这里编写获取CPU使用率的代码,可以调用系统命令获取CPU使用率数据
// 返回一个0到1之间的浮点数,表示CPU使用率百分比
return 0.75
}
func queryDB(clnt client.Client, cmd string) (res []client.Result, err error) {
q := client.Query{
Command: cmd,
Database: "mydb",
}
if response, err := clnt.Query(q); err == nil {
if response.Error() != nil {
return res, response.Error()
}
res = response.Results
} else {
return res, err
}
return res, nil
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.