关于go:go-v120-使用influxdb124-老版本-查询数据

32次阅读

共计 2063 个字符,预计需要花费 6 分钟才能阅读完成。


package main

import (
    "encoding/json"
    "fmt"
    "github.com/gin-gonic/gin"
    client "github.com/influxdata/influxdb1-client/v2"
    "net/http"
    "os"
    "time"
)

// 创立一个 client
func ExampleClient()client.Client {
    // NOTE: this assumes you've setup a user and have setup shell env variables,
    // namely INFLUX_USER/INFLUX_PWD. If not just omit Username/Password below.
    cli, err := client.NewHTTPClient(client.HTTPConfig{
        Addr:     "http://10.xx.x5.x5:8086",
        Username: os.Getenv("ltx"),
        Password: os.Getenv("x6xxx"),
    })
    if err != nil {fmt.Println("Error creating InfluxDB Client:", err.Error())
    }
    return cli
}

// 把数据写入 influxdb
func ExampleClient_write(cli client.Client) {
    // Make client
    c, err := client.NewHTTPClient(client.HTTPConfig{Addr: "http://10.xx.x5.x5:8086",})
    if err != nil {fmt.Println("Error creating InfluxDB Client:", err.Error())
    }
    defer c.Close()

    // Create a new point batch
    bp, _ := client.NewBatchPoints(client.BatchPointsConfig{
        Database:  "BumbleBeeTuna",// 数据库名
        Precision: "s",// 工夫精度秒
    })
    // Create a point and add to batch
    tags := map[string]string{"cpu": "cpu-total"}// 查问的索引
    fields := map[string]interface{}{
        "idle":   10.1,
        "system": 53.3,
        "user":   46.6,
    }// 记录值
    pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now())// 将创立的表名为 cpu_usage 的表以及内容字段放入 pt
    if err != nil {fmt.Println("Error:", err.Error())
    }
    bp.AddPoint(pt)// 把表放入创立的 point 中

    // Write the batch
    c.Write(bp)// 写入创立的 client 中
}
// 查问
func ExampleClient_query(cli client.Client) []client.Result {
    // Make client
    c, err := client.NewHTTPClient(client.HTTPConfig{Addr: "http://10.xx.x5.x5:8086",})
    if err != nil {fmt.Println("Error creating InfluxDB Client:", err.Error())
    }
    defer c.Close()

    q := client.NewQuery("SELECT * FROM ipad_electricitytable where time > now() - 3m and electricity < 90 group by ip order by time desc limit 1", "ipad", "ns")
    if response, err := c.Query(q); err == nil && response.Error() == nil {//fmt.Println(response.Results)
        var lll []client.Result
        ll,_ := json.Marshal(response.Results)
        err = json.Unmarshal(ll, &lll)

        return lll
    }else {return nil}

}



func main() {r := gin.Default()
    r.GET("/test56", func(c *gin.Context) {conn := ExampleClient()
        mes:=ExampleClient_query(conn)
        c.JSON(http.StatusOK, gin.H{"message": mes,})
    })
    //conn := ExampleClient()
    ////ExampleClient_write(conn)
    //ExampleClient_query(conn)
    r.Run() // 默认在本地 8080 端口启动服务}

正文完
 0