influxdb 2.0安装和使用

原创
2021/04/15 13:55
阅读数 1.7W
  • influxdb是一个开源的时序数据库,开源版本只支持单机+高可用,商业版本才支持集群(横向扩展/分片)功能
  • 安装参考 https://docs.influxdata.com/influxdb/v2.0/get-started/?t=Docker
    cd ~
    
    mkdir influxdb-data
    
    sudo docker run -d \
    --name influxdb \
    --restart always \
    -p 8086:8086 \
    --volume /home/your_name/influxdb-data:/var/lib/influxdb2 \
    influxdb:2.0.8
    
  • 代码参考(golang)
package main

import (
	"context"
	"fmt"
	"log"
	"math/rand"
	"time"

	influxdb2 "github.com/influxdata/influxdb-client-go/v2"
)

func main() {
	// You can generate a Token from the "Tokens Tab" in the UI
	const token = "Uok6jfbNdqUWSIZyaH0aqxrSvSC1vg5WS5UyJHWciqY_FvkfOGxqHox_EbbvJQwRXQ770gUQqD1ZcXWvTjPFrA=="
	const bucket = "test"
	const org = "you_org"

	client := influxdb2.NewClient("http://192.168.1.11:8086", token)
	// always close client at the end
	defer client.Close()
	write(client, bucket, org)
}

func write(client influxdb2.Client, bucket, org string) {
	// get non-blocking write client
	writeAPI := client.WriteAPI(org, bucket)

	now := time.Now()
	times := 0
	// 10个设备 (60*60*24*365)*10=315360000。约3.1亿条数据
	for i := 0; i < 10; i++ {
		// 过去一年
		start := now.Add(-8760 * time.Hour)
		for now.After(start) {
			// write line protocol
			p := influxdb2.NewPointWithMeasurement("设备信息").
				AddTag("设备id", fmt.Sprint(i)).
				AddField("压力", rand.Float32()*100).
				AddField("温度", rand.Float32()*30).SetTime(start)
			start = start.Add(1 * time.Second)
			writeAPI.WritePoint(p)
			if times == 10000 {
				log.Printf("当前设备id: %s, 本次写入 %d 条, 最后一条时间: %s", fmt.Sprint(i), times, start.Format("2006-01-02 15:04:05"))
				times = 0
				// Flush writes
				writeAPI.Flush()
			} else {
				times++
			}
		}
		// Flush writes
		writeAPI.Flush()
	}

}

func query(client influxdb2.Client, bucket, org string) {
	query := fmt.Sprintf("from(bucket:\"%v\")|> range(start: -1h) |> filter(fn: (r) => r._measurement == \"stat\")", bucket)
	// Get query client
	queryAPI := client.QueryAPI(org)
	// get QueryTableResult
	result, err := queryAPI.Query(context.Background(), query)
	if err == nil {
		// Iterate over query response
		for result.Next() {
			// Notice when group key has changed
			if result.TableChanged() {
				fmt.Printf("table: %s\n", result.TableMetadata().String())
			}
			// Access data
			fmt.Printf("%s value: %v\n", result.Record().Field(), result.Record().Value())
		}
		// check for an error
		if result.Err() != nil {
			fmt.Printf("query parsing error: %s\n", result.Err().Error())
		}
	} else {
		panic(err)
	}
}
  • dashboard

展开阅读全文
打赏
0
1 收藏
分享
加载中
更多评论
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部