一 . 安装
1.mac肯定是brew安装啦
brew update
brew install influxdb
ln -sfv /usr/local/opt/influxdb/*.plist ~/Library/LaunchAgents
配置文件在/etc/influxdb/influxdb.conf ,如果没有就将/usr/local/etc/influxdb.conf 拷一个过去
cache-max-memory-size是用来配置缓存的
#启动服务
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.influxdb.plist
#停止服务
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.influxdb.plist
#前台启动
influxd -config /usr/local/etc/influxdb.conf
#查看influxdb运行配置
influxd config
2.启动客户端
influx -precision rfc3339
3.基本操作
-
名词解释
Point由时间戳(time)、数据(field)、标签(tags)组成。
这里不得不提另一个名词[series]:所有在数据库中的数据,都需要通过图表来展示,而这个series表示这个表里面的数据,可以在图表上画成几条线:通过tags排列组合算出来。
select series from xxx
- 简单的增
CREATE DATABASE mydb
use mydb
insert weather,altitude=1000,area=北 temperature=11,humidity=-4
#weather : 表名
#altitude=1000,area=北 : tag
#temperature=11,humidity=-4 :field
- 查
SELECT * FROM weather ORDER BY time DESC LIMIT 3
二 . go调用
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)
}
fmt.Println("==========",res)
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)
}
}
有疑问加站长微信联系(非本文作者)