本文主要通过go语言对influxdb做一个简单的创建表以及插入一条数据的操作,代码如下所示(使用到了一个插件,可通过go get进行安装):

 

package main

import (
	"fmt"
	"github.com/influxdata/influxdb/client/v2"
	"log"
	"time"
)

const (
	MyDB     = "test"
	username = "admin"
	password = ""
)

func main() {
	conn, err := client.NewHTTPClient(client.HTTPConfig{
		Addr:     "http://127.0.0.1:8086",
		Username: username,
		Password: password,
	})

	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(conn)

	bp, err := client.NewBatchPoints(client.BatchPointsConfig{
		Database:  MyDB,
		Precision: "s",
	})

	if err != nil {
		log.Fatal(err)
	}

	tags := map[string]string{"name": "xc"}
	fields := map[string]interface{}{
		"id":   1,
		"sex":  1,
		"pass": 0707,
	}

	pt, err := client.NewPoint("myuser", tags, fields, time.Now())
	if err != nil {
		log.Fatal(err)
	}
	bp.AddPoint(pt)

	if err := conn.Write(bp); err != nil {
		log.Fatal(err)
	}
}

 

补充:

 

经过查看官方文档以及实际操作,代码总结如下,其实对于influxdb也只是涉及到insert与query,代码如下,完成插入与查询两个函数。可参考官方文档:点击打开链接

 

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"time"

	"github.com/influxdata/influxdb1-client/v2"
)

const (
	MyDB          = "test"
	username      = "admin"
	password      = ""
	MyMeasurement = "cpu_usage"
)

func main() {
	conn := connInflux()
	fmt.Println(conn)

	//insert
	WritesPoints(conn)

	//获取10条数据并展示
	qs := fmt.Sprintf("SELECT * FROM %s LIMIT %d", MyMeasurement, 10)
	res, err := QueryDB(conn, qs)
	if err != nil {
		log.Fatal(err)
	}

	for i, row := range res[0].Series[0].Values {
		t, err := time.Parse(time.RFC3339, row[0].(string))
		if err != nil {
			log.Fatal(err)
		}
		//fmt.Println(reflect.TypeOf(row[1]))
		valu := row[2].(json.Number)
		log.Printf("[%2d] %s: %s\n", i, t.Format(time.Stamp), valu)
	}
}

func connInflux() client.Client {
	cli, err := client.NewHTTPClient(client.HTTPConfig{
		Addr:     "http://127.0.0.1:8086",
		Username: username,
		Password: password,
	})
	if err != nil {
		log.Fatal(err)
	}
	return cli
}

//query
func QueryDB(cli client.Client, cmd string) (res []client.Result, err error) {
	q := client.Query{
		Command:  cmd,
		Database: MyDB,
	}
	if response, err := cli.Query(q); err == nil {
		if response.Error() != nil {
			return res, response.Error()
		}
		res = response.Results
	} else {
		return res, err
	}
	return res, nil
}

//Insert
func WritesPoints(cli client.Client) {
	bp, err := client.NewBatchPoints(client.BatchPointsConfig{
		Database:  MyDB,
		Precision: "s",
	})
	if err != nil {
		log.Fatal(err)
	}

	tags := map[string]string{"cpu": "ih-cpu"}
	fields := map[string]interface{}{
		"idle":   20.1,
		"system": 43.3,
		"user":   86.6,
	}

	pt, err := client.NewPoint(
		"cpu_usage",
		tags,
		fields,
		time.Now(),
	)
	if err != nil {
		log.Fatal(err)
	}
	bp.AddPoint(pt)

	if err := cli.Write(bp); err != nil {
		log.Fatal(err)
	}
}

 

 

 

 

 

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐