golang--influxdb数据库

简单结构:

项目名称:tttt

----service

  ----base.go

----main.go

驱动:github.com/influxdata/influxdb/client/v2

base.go:

package service

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

)

var Service *serviceProxy
const databaseName = "testDB"

type serviceProxy struct {
    influx   client.Client
}

func init() {
    Service = new(serviceProxy)
    initInflux()
}

func createInfluxTable() {
    now := time.Now()
    bp, _ := client.NewBatchPoints(client.BatchPointsConfig{
        Precision: "ms",
        Database:  databaseName,
    })

    point, _ := client.NewPoint(
        "tableName",
        map[string]string{"fieldName": "value"},
        map[string]interface{}{"fieldName": "value"}, now)
    bp.AddPoint(point)

    Service.influx.Write(bp)
}

func initInflux() {
    opt, err := url.Parse("influx://leaniot:leaniot@127.0.0.1:8086")
    if err != nil {
        panic(err)
    }
    pwd, _ := opt.User.Password()
    Service.influx, err = client.NewHTTPClient(client.HTTPConfig{
        Addr:     fmt.Sprintf("http://%s", opt.Host),
        Username: opt.User.Username(),
        Password: pwd,
        Timeout:  time.Second * 5,
    })
    if err != nil {
        panic(err)
    }



    // 建库
    createDbSQL := client.NewQuery(fmt.Sprintf("CREATE DATABASE %s", databaseName), "", "")
    // 建表

    createInfluxTable()

    createCQ2m := client.NewQuery(fmt.Sprintf("CREATE CONTINUOUS QUERY cq_exchanger_2m ON %s "+
        "BEGIN SELECT mean(value) AS value INTO raw_data_2m FROM raw_data GROUP BY unique_id, time(2m) END", databaseName), databaseName, "")
    createCQ1h := client.NewQuery(fmt.Sprintf("CREATE CONTINUOUS QUERY cq_exchanger_1h ON %s "+
        "BEGIN SELECT mean(value) AS value INTO raw_data_1h FROM raw_data GROUP BY unique_id, time(1h) END", databaseName), databaseName, "")
    // 过期策略
    createRPSQL := client.NewQuery(fmt.Sprintf("CREATE RETENTION POLICY default ON %s DURATION 360d REPLICATION 1 DEFAULT", databaseName), databaseName, "")
    if _, err := Service.influx.Query(createDbSQL); err != nil {
        panic(err)
    }
    if _, err := Service.influx.Query(createCQ2m); err != nil {
        panic(err)
    }
    if _, err := Service.influx.Query(createCQ1h); err != nil {
        panic(err)
    }
    if _, err := Service.influx.Query(createRPSQL); err != nil {
        panic(err)
    }

    println("influxDB services started")

}

func (s *serviceProxy) Close() {
    s.influx.Close()
}

 

main.go:

import (
    "github.com/gin-gonic/gin"
    "tttt/service"
)


func main() {
    defer func() {
        service.Service.Close()  // 程序停止后,关闭连接
    }()
    route := gin.Default()
    route.Run("0.0.0.0:5000")
}

 

posted @ 2018-11-26 13:55  静静别跑  阅读(4553)  评论(0编辑  收藏  举报