1. 创建测试用的数据库
IP:8086
2. 下载 influxdb-client-go
go get github.com/influxdata/influxdb-client-go
3 编写代码
连接TSDB&&插入point
package main
import (
"fmt"
"time"
influxdb2 "github.com/influxdata/influxdb-client-go/v2"
)
func main() {
tsdb := influxdb2.NewClient("http://IP:8086",
"UD3qST2Zu57fMZVmxaFTIxAhp6XA_CXt7YuUyQouyYfoAJtpAkH_CzmHP6BBLGY-XDAJVCthTClSLz0j2eg_Cg==")
// get non-blocking write client
writeAPI := tsdb.WriteAPI("xuehu96", "test")
// 第一种写入方法
writeAPI.WriteRecord(fmt.Sprintf("MEASUREMENT,unit=temperature avg=%f,max=%f", 4.5, 5.5))
writeAPI.Flush()
// 第二种写入方法
p1 := influxdb2.NewPoint("MEASUREMENT",
map[string]string{"unit": "temperature"},
map[string]interface{}{"avg": 24.5, "max": 45.1},
time.Now())
writeAPI.WritePoint(p1)
writeAPI.Flush()
// 第三种写入方法 (这种好用)
p := influxdb2.NewPointWithMeasurement("MEASUREMENT").
AddTag("unit", "precent").
AddField("avg", 23.2).
AddField("max", 88.8).
SetTime(time.Now())
writeAPI.WritePoint(p)
writeAPI.Flush()
// TODO:在这里写查询代码
defer tsdb.Close()
}
其中,第三种写入方法比较好,保留第三种写入方法,前两种注释掉
接下来是数据查询(在上一段代码 //TODO处写以下代码)
// 查询
queryAPI := tsdb.QueryAPI("xuehu96")
// Flux查询语句 相当于sql语句
query := `from(bucket: "test")
|> range(start: -1h)
|> filter(fn: (r) => r["_measurement"] == "TestData")
|> filter(fn: (r) => r["_field"] == "max" or r["_field"] == "avg")
`
// 查询结果
result, err := queryAPI.Query(context.Background(), query)
if err != nil {
log.Fatalln(err.Error())
}
// 解析结果
for result.Next() {
// 类型 : string, float64, string, time.Time
log.Printf("field: %v, value :%v, unit:%v, time:%v\n", result.Record().Field(), result.Record().Value(), result.Record().ValueByKey("unit"), result.Record().Time())
/* 打印结果
2022/04/08 11:11:44 field: avg, value :99.9, unit:precent, time:2022-04-08 03:11:37.4553546 +0000 UTC
2022/04/08 11:11:44 field: avg, value :66.9, unit:precent, time:2022-04-08 03:11:44.7049963 +0000 UTC
2022/04/08 11:11:44 field: max, value :40.8, unit:precent, time:2022-04-08 03:11:37.4553546 +0000 UTC
2022/04/08 11:11:44 field: max, value :55.8, unit:precent, time:2022-04-08 03:11:44.7049963 +0000 UTC
*/
}
if result.Err() != nil {
log.Printf("query parsing error: %s \n", result.Err().Error())
}