golang influxdb2读写封装

==下载依赖==

go get github.com/influxdata/influxdb-client-go

 

如果下载不下来,可以通过控制台输入

go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn

 

==官网地址==

https://docs.influxdata.com/influxdb/v2.0/api-guide/client-libraries/go/

 

==程序样例==

【数据写入:方式一】

package main

import (
    influxdb2 "github.com/influxdata/influxdb-client-go"
    "time"
)

func main() {
    org := "qch"
    bucket := "qch-bucket"
    token := "xxxx=="
    measurement := "data_up"
    client := influxdb2.NewClient("http://xx.xx.xx.xx:8086", token)
    defer client.Close()

    writeAPI := client.WriteAPI(org, bucket)

    tags := map[string]string{
        "deviceId": "d1",
        "pointId":  "AR_TEST_VAR1",
    }
    fields := map[string]interface{}{
        "value": 24.5,
    }
    point1 := influxdb2.NewPoint(measurement, tags, fields, time.Now())
    writeAPI.WritePoint(point1)
}

 

【数据写入:方式二】

package main

import (
    influxdb2 "github.com/influxdata/influxdb-client-go"
    "math/rand"
    "time"
)

func main() {
    org := "qch"
    bucket := "qch-bucket"
    token := "xxx"
    measurement := "data_up"
    client := influxdb2.NewClient("http://xx.xx.xx.xx:8086", token)
    defer client.Close()

    writeAPI := client.WriteAPI(org, bucket)

    deviceId := "d1"
    pointIdList := []string{
        "AR_TEST_VAR1",
        "AR_TEST_VAR2",
    }

    rand.Seed(time.Now().UnixNano())
    for _, pointId := range pointIdList {
        point2 := influxdb2.NewPointWithMeasurement(measurement).
            AddTag("deviceId", deviceId).
            AddTag("pointId", pointId).
            AddField("value", rand.Float64()).
            SetTime(time.Now())
        writeAPI.WritePoint(point2)
    }
    writeAPI.Flush()
}

 

【数据读取】

package main

import (
    "context"
    "errors"
    influxdb2 "github.com/influxdata/influxdb-client-go"
    "log"
    "strconv"
    "strings"
    "time"
)

const Org = "qch"
const BucketId = "qch-bucket"
const Measurement = "data_up"
const FormatLong = "2006-01-02 15:04:05"
const Token = "xxxx"
const Url = "http://xx.xx.xx.xx:8086"

func main() {

    var queryParam QueryDataParam
    queryParam.BucketId = BucketId
    queryParam.DeviceId = "d1"
    queryParam.StartTime = "2022-05-05 17:13:00"
    queryParam.StopTime = "2022-05-07 17:13:00"
    queryParam.PointIdList = []string{
        "AR_TEST_VAR1",
        "AR_TEST_VAR2",
    }

    data, err := DoQueryData(queryParam)
    if err != nil {
        return
    }
    log.Println(data)
}

func DoQueryData(queryParam QueryDataParam) ([]QueryResult, error) {
    client := influxdb2.NewClient(Url, Token)
    defer client.Close()

    start, err := StrToTime(queryParam.StartTime)
    if err != nil {
        log.Println(err.Error())
        return nil, err
    }
    stop, err := StrToTime(queryParam.StopTime)
    if err != nil {
        log.Println(err.Error())
        return nil, err
    }

    queryStr := ""
    queryStr = AppendFrom(queryStr, queryParam.BucketId)
    queryStr = AppendRange(queryStr, start, stop)
    queryStr = AppendFilterMeasurement(queryStr, Measurement)
    queryStr = AppendFilterField(queryStr)
    queryStr = AppendFilterTag(queryStr, queryParam.DeviceId, queryParam.PointIdList)
    log.Println(queryStr)

    queryAPI := client.QueryAPI(Org)
    queryTableResult, err := queryAPI.Query(context.Background(), queryStr)
    if err != nil {
        log.Println(err.Error())
        return nil, err
    }
    if queryTableResult.Err() != nil {
        log.Println(err.Error())
        return nil, err
    }

    var result []QueryResult
    for queryTableResult.Next() {
        record := queryTableResult.Record()
        timeStr := TimeToStr(record.Time())
        queryResult := QueryResult{}
        queryResult.Time = timeStr
        queryResult.Value = record.Value()
        queryResult.Point = record.Values()["pointId"].(string)
        result = append(result, queryResult)
    }

    return result, err
}

type QueryDataParam struct {
    StartTime   string   `json:"startTime"`
    StopTime    string   `json:"stopTime"`
    BucketId    string   `json:"bucketId"`
    DeviceId    string   `json:"deviceId"`
    PointIdList []string `json:"pointIdList"`
}

type QueryResult struct {
    Time  string      `json:"time"`
    Point string      `json:"point"`
    Value interface{} `json:"value"`
}

func AppendFrom(query, bucketId string) string {
    template := " from(bucket:\"{bucketId}\") "
    template = strings.Replace(template, "{bucketId}", bucketId, -1)
    return query + template
}

func AppendRange(query string, startTime, stopTime time.Time) string {
    template := " |> range(start: {start}, stop: {stop}) "
    template = strings.Replace(template, "{start}", strconv.FormatInt(startTime.Unix(), 10), -1)
    template = strings.Replace(template, "{stop}", strconv.FormatInt(stopTime.Unix(), 10), -1)
    return query + template
}

func AppendFilterMeasurement(query, measurement string) string {
    template := " |> filter(fn: (r) => r[\"_measurement\"] == \"{measurement}\") "
    template = strings.Replace(template, "{measurement}", measurement, -1)
    return query + template
}

func AppendFilterField(query string) string {
    template := " |> filter(fn: (r) => r[\"_field\"] == \"value\") "
    return query + template
}

func AppendFilterTag(query, deviceId string, pointIdList []string) string {
    templateDevice := " |> filter(fn: (r) => r[\"deviceId\"] == \"{deviceId}\") "
    templatePointMain := " |> filter(fn: (r) => {tagStr}) "
    templatePointSub := " r[\"pointId\"] == \"{pointId}\" "

    index := 0
    templatePoint := ""
    for _, pointId := range pointIdList {
        str := strings.Replace(templatePointSub, "{pointId}", pointId, -1)
        if index > 0 {
            templatePoint = templatePoint + " or "
        }
        templatePoint = templatePoint + str
        index++
    }

    templateDevice = strings.Replace(templateDevice, "{deviceId}", deviceId, -1)
    templatePointMain = strings.Replace(templatePointMain, "{tagStr}", templatePoint, -1)
    return query + templateDevice + templatePointMain
}

func TimeToStr(time time.Time) string {
    return time.Format(FormatLong)
}

func StrToTime(timeStr string) (time.Time, error) {
    parse, err := time.Parse(FormatLong, timeStr)
    if err != nil {
        log.Println(err.Error())
        return time.Time{}, errors.New("日期转换异常")
    }
    return parse, nil
}

 

posted @ 2022-04-21 16:10  大墨垂杨  阅读(225)  评论(0编辑  收藏  举报