influxdb

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

MGIN InfluxDB 插件

基于官方 influxdb-client-go/v2 (v2.14.0) 的 MGIN 时序数据库插件,模块名 github.com/maczh/influxdb。

面向 InfluxDB 2.x(bucket / org / token 模型):

  • 写入(行协议 line protocol)天然兼容 InfluxDB 3.x;
  • Flux 查询适用于 2.x;3.x 已移除 Flux,需用 SQL / InfluxQL,可通过 Client() 逃逸到原始客户端实现。

遵循与 maczh/hive、maczh/hbase、maczh/mssql 一致的 MGIN 插件契约:Init([]byte) / Check() error / Close(),支持单连接与多连接,配置用 koanf 读取 go.data.influxdb*,日志用 gologger。

安装

go get github.com/maczh/influxdb

要求 Go 1.21+(本仓库 go.mod 使用 go 1.25.7)。

注册到 MGIN

import "github.com/maczh/influxdb"

app.MGin.UsePlugin("influxdb", influxdb.InfluxDB)

本地配置(go.config):

go:
  config:
    used: influxdb
    prefix: influxdb

配置

单连接
go:
  data:
    influxdb:
      url: "http://localhost:8086"
      token: "my-super-secret-token"
      org: "my-org"
      bucket: "my-bucket"
      batchSize: 5000      # 异步批量写入大小 (WriteAPI 生效)
      flushInterval: 1000  # 批量刷新间隔(毫秒)
      timeout: 5           # HTTP 请求超时(秒)
      maxRetries: 3        # 失败重试次数
      gzip: true           # 启用 gzip
      precision: "ns"      # 时间戳精度 ns/us/ms/s
多连接(多服务端 / 多 org-bucket)
go:
  data:
    influxdb_multidb: true
    influxdb_dbNames: "db1,db2"
    influxdb_db1:
      url: "http://host1:8086"
      token: "token1"
      org: "org1"
      bucket: "bucket1"
    influxdb_db2:
      url: "http://host2:8086"
      token: "token2"
      org: "org2"
      bucket: "bucket2"

多连接模式下,所有写/查方法的第一参数 tag 传入连接名(如 "db1")。

API

方法 说明
Write(tag, measurement, tags, fields, ts) 阻塞写入一条数据点(measurement + tags + fields + timestamp)
WritePoint(tag, *write.Point) 写入已构造的 write.Point
WriteRecord(tag, lines...) 以行协议写入一条或多条记录
Query(tag, flux) 执行 Flux 查询,返回 *api.QueryTableResult(用毕 Close())
QueryRaw(tag, flux) 执行 Flux 查询,返回原始 CSV 字符串
Client(tag...) 返回底层 influxdb2.Client(逃逸用,如 3.x 的 InfluxQL/SQL、管理 API)
Health(tag...) 返回 *domain.HealthCheck 服务端健康信息
GetConnection(dbName...) 返回底层 influxdb2.Client
IsMultiDB() / ListConnNames() 多连接状态
Check() / Close() 健康检查(失败重建)/ 关闭
写入示例
tags := map[string]string{"host": "serverA", "region": "cn"}
fields := map[string]interface{}{"cpu": 0.64, "mem": 1024.5, "online": true}
err := influxdb.InfluxDB.Write("", "metrics", tags, fields, time.Now())

或用行协议:

err := influxdb.InfluxDB.WriteRecord("", "metrics,host=serverA,region=cn cpu=0.64,mem=1024.5 1700000000000000000")
查询示例(Flux,2.x)
result, err := influxdb.InfluxDB.Query("", `from(bucket:"my-bucket")
  |> range(start: -1h)
  |> filter(fn: (r) => r._measurement == "metrics")`)
if err != nil { /* ... */ }
defer result.Close()
for result.Next() {
    r := result.Record()
    fmt.Printf("time=%v field=%s value=%v\n", r.Time(), r.Field(), r.Value())
}
if result.Err() != nil { /* ... */ }
InfluxDB 3.x 查询(InfluxQL / SQL)

InfluxDB 3.x 移除 Flux,请用 v1 兼容的 InfluxQL 端点或 SQL。通过 Client() 获取原生客户端后自行请求:

cli, _ := influxdb.InfluxDB.Client("")
// 用 cli.HTTPService() / cli.ServerURL() 走 /query (InfluxQL) 或 /api/v3/query_sql 端点

对象化 CRUD / 组合查询 / 聚合查询

仿 GORM 的链式会话 InfluxSession,把 Go 结构体映射为 InfluxDB 的 measurement / tag / field,支持对象化写入、组合过滤查询与窗口聚合查询。

结构体标签
type CpuMetric struct {
    Time   time.Time `influx:"time"`          // 时间戳列 _time (不写则用 time.Now())
    Host   string    `influx:"tag:host"`      // 标签列 host
    Region string    `influx:"tag:region"`   // 标签列 region
    Usage  float64   `influx:"field:usage"`  // 数值列 usage
    Mem    float64   `influx:"field:mem"`    // 数值列 mem
}

// 可选: 实现 InfluxModel 接口提供 measurement 名 (优先级高于标签与类型名)
func (CpuMetric) Measure() string { return "cpu" }
标签 含义
influx:"time" / "timestamp" 时间戳字段(写入默认 time.Now())
influx:"tag:列名" 标签列;只写 tag 时列名取字段名小写
influx:"field:列名" 数值列;只写 field 时列名取字段名小写
influx:"measurement:名" 在该字段上固定 measurement 名
influx:"-" 忽略该字段

measurement 推导优先级:Table("名") > Measure() 方法 > influx:"measurement:名" > 类型名小写。

对象化写入
m := influxdb.InfluxDB.Model(&CpuMetric{})
err := m.Create(&CpuMetric{Time: time.Now(), Host: "s1", Region: "cn", Usage: 0.9, Mem: 0.5})
// 批量
err = m.CreateInBatches([]CpuMetric{...}, 100)
组合查询(过滤 + 时间范围 + 排序 + 分页)
var rows []CpuMetric
err := influxdb.InfluxDB.Table("cpu").
    Tag("host", "s1").            // r.host == "s1"
    TagIn("region", "cn", "us").  // (r.region == "cn" or r.region == "us")
    Fields("usage", "mem").       // r._field == "usage" or r._field == "mem"
    TimeRange(t1, t2).            // 绝对区间
    // .Since(time.Hour)          // 最近 1h
    OrderByTime(false).           // 按时间倒序
    Limit(100).                   // 限制 100 行
    Find(&rows)

Where(pred) 可追加任意原始 Flux 谓词片段(引用 r._field / r._value / 标签列)。

聚合查询(窗口聚合 + 分组 + 填充)
var agg []CpuMetric
err := influxdb.InfluxDB.Table("cpu").
    Fields("usage", "mem").
    Aggregate(influxdb.AggMean, "1m"). // 每 1m 窗口求均值
    GroupBy("host").                   // 按 host 分组
    Fill("previous").                  // 空窗口用上一值填充
    Find(&agg)

聚合函数常量:AggMean/AggSum/AggCount/AggMin/AggMax/AggMedian/AggStddev/AggSpread/AggFirst/AggLast/AggMode/AggIntegral/AggDistinct。

  • Aggregate(fn, every) → aggregateWindow(every, fn)(窗口聚合)
  • Func(fn) → 全局聚合(无窗口,如 |> count())
  • Window(every) → 仅设窗口(默认 mean)
  • GroupBy(cols...) / Fill("none"|"previous"|"0"|"linear") / OrderByTime(asc)
计数 / 取首条 / 删除
n, _ := influxdb.InfluxDB.Table("cpu").Tag("host", "s1").Since(time.Hour).Count() // 匹配行数
var one CpuMetric
influxdb.InfluxDB.Table("cpu").Tag("host", "s1").OrderByTime(false).First(&one)    // 最新一条

// 删除 (InfluxDB 2.x; 3.x 不支持)
influxdb.InfluxDB.Table("cpu").Tag("host", "s1").Since(time.Hour).Delete()
原生 Flux(逃逸 / 高级)
influxdb.InfluxDB.Table("cpu").Raw(`from(bucket:"my-bucket") |> range(start:-1h) ...`).Find(&rows)
flux := influxdb.InfluxDB.Table("cpu").Tag("host","s1").Limit(10).Explain() // 查看拼装的 Flux
扫描规则

Flux 列式结果会按 _time + 标签聚合为「一行」,再按结构体的 influx 标签映射到字段(标签→tag 字段、数值→field 字段、_time→time 字段),自动做数值/字符串/布尔/时间类型转换。

注意事项

  • 版本兼容:写兼容 2.x 与 3.x;Flux(Query/QueryRaw)仅 2.x 可用,3.x 请用 SQL/InfluxQL。
  • Token 权限:写入需要 write、查询需要 read 权限(对目标 bucket)。
  • 行协议精度:precision 决定时间戳单位,需与写入时传入的 time.Time 精度一致(默认纳秒)。
  • 查询结果释放:Query 返回的 *api.QueryTableResult 用完务必 Close(),避免连接泄漏。

验证状态

  • go build ./... ✅、go vet ./... ✅、gofmt -l . ✅
  • go test -run 'TestInfluxDB|TestParseModel|TestMeasurementDerivation|TestExplainFlux|TestExplainAggregate|TestInfluxDBORM' ✅ 纯函数/拼装测试通过,无 InfluxDB 时端到端用例自动 SKIP
  • 未做真实建连/读写端到端验证(环境无 InfluxDB 服务)

Documentation

Index

Constants

View Source
const (
	AggMean     = "mean"
	AggSum      = "sum"
	AggCount    = "count"
	AggMin      = "min"
	AggMax      = "max"
	AggMedian   = "median"
	AggStddev   = "stddev"
	AggSpread   = "spread"
	AggFirst    = "first"
	AggLast     = "last"
	AggMode     = "mode"
	AggIntegral = "integral"
	AggDistinct = "distinct"
)

聚合函数名 (Flux 内置)。

Variables

View Source
var InfluxDB = &influxDB{}

InfluxDB 全局插件实例。用法: app.MGin.UsePlugin("influxdb", influxdb.InfluxDB)

Functions

This section is empty.

Types

type InfluxModel

type InfluxModel interface {
	Measure() string
}

InfluxModel 可选接口: 实现 Measure() 即可在 Model() 时提供 measurement 名, 优先级高于 `influx:"measurement:xxx"` 标签与类型名小写回退。

type InfluxSession

type InfluxSession struct {
	// contains filtered or unexported fields
}

InfluxSession 是 GORM 风格链式会话, 与 *gorm.DB 类似。 由 influxDB.Model() / influxDB.Table() 创建, 方法均返回自身以支持链式调用。

func (*InfluxSession) Aggregate

func (s *InfluxSession) Aggregate(fn, every string) *InfluxSession

Aggregate 窗口聚合: 每 every 时长, 使用 fn 函数 (如 mean/sum)。

func (*InfluxSession) All

func (s *InfluxSession) All(out interface{}) error

All 同 Find。

func (*InfluxSession) Connection

func (s *InfluxSession) Connection(name string) *InfluxSession

Connection 选择多连接模式下的连接名。

func (*InfluxSession) Count

func (s *InfluxSession) Count() (int64, error)

Count 返回匹配行数 (执行查询并统计原始结果行, 不受 Limit 影响)。

func (*InfluxSession) Create

func (s *InfluxSession) Create(model interface{}) error

Create 写入单个结构体对象。

func (*InfluxSession) CreateInBatches

func (s *InfluxSession) CreateInBatches(models interface{}, batch int) error

CreateInBatches 批量写入切片对象 (batch 仅作语义参数, 底层为阻塞逐条写入)。

func (*InfluxSession) Delete

func (s *InfluxSession) Delete() error

Delete 按当前过滤 / 时间范围删除数据 (influxDB 2.x; 3.x 不支持)。

func (*InfluxSession) Explain

func (s *InfluxSession) Explain() string

Explain 返回将要执行的 Flux (调试用)。

func (*InfluxSession) Field

func (s *InfluxSession) Field(name string) *InfluxSession

Field 限定要查询的数值列 _field == "name"。

func (*InfluxSession) Fields

func (s *InfluxSession) Fields(names ...string) *InfluxSession

Fields 限定多个数值列。

func (*InfluxSession) Fill

func (s *InfluxSession) Fill(mode string) *InfluxSession

Fill 设置空窗口填充模式: "none" / "previous" / "0" / "linear"。

func (*InfluxSession) Find

func (s *InfluxSession) Find(out interface{}) error

Find 执行查询并将结果扫描进 out (指向切片的指针)。

func (*InfluxSession) First

func (s *InfluxSession) First(out interface{}) error

First 取第一条结果写入 out。

func (*InfluxSession) Func

func (s *InfluxSession) Func(fn string) *InfluxSession

Func 全局聚合 (无窗口): |> mean() / |> count() 等。

func (*InfluxSession) GroupBy

func (s *InfluxSession) GroupBy(cols ...string) *InfluxSession

GroupBy 重新分组 (指定列名, 如 "host")。

func (*InfluxSession) Limit

func (s *InfluxSession) Limit(n int) *InfluxSession

Limit 限制返回行数。

func (*InfluxSession) Model

func (s *InfluxSession) Model(model interface{}) *InfluxSession

Model 设置模板结构体。

func (*InfluxSession) OrderByTime

func (s *InfluxSession) OrderByTime(asc bool) *InfluxSession

OrderByTime 按时间排序 (asc=true 升序, 默认 true)。

func (*InfluxSession) Raw

func (s *InfluxSession) Raw(flux string) *InfluxSession

Raw 直接使用用户提供的 Flux (忽略自动拼装, 但仍会扫描进结构体)。

func (*InfluxSession) Save

func (s *InfluxSession) Save(model interface{}) error

Save 同 Create。

func (*InfluxSession) Since

Since 表示最近一段时间 (如 time.Hour)。

func (*InfluxSession) Start

func (s *InfluxSession) Start(t time.Time) *InfluxSession

Start 设置开始时间。

func (*InfluxSession) Stop

func (s *InfluxSession) Stop(t time.Time) *InfluxSession

Stop 设置结束时间。

func (*InfluxSession) Table

func (s *InfluxSession) Table(name string) *InfluxSession

Table 直接指定 measurement。

func (*InfluxSession) Tag

func (s *InfluxSession) Tag(key, val string) *InfluxSession

Tag 增加标签等值过滤: r.<key> == "<val>"。

func (*InfluxSession) TagIn

func (s *InfluxSession) TagIn(key string, vals ...string) *InfluxSession

TagIn 增加标签枚举过滤: (r.<key> == "a" or r.<key> == "b")。

func (*InfluxSession) TimeRange

func (s *InfluxSession) TimeRange(start, stop time.Time) *InfluxSession

TimeRange 设置绝对时间范围 (start/stop)。

func (*InfluxSession) Until

Until 表示数据截至 d 之前 (stop = now - d)。

func (*InfluxSession) Where

func (s *InfluxSession) Where(pred string) *InfluxSession

Where 追加原始 Flux 谓词片段 (引用 r._measurement / r._field / r._value / 标签列)。

func (*InfluxSession) Window

func (s *InfluxSession) Window(every string) *InfluxSession

Window 仅设置聚合窗口时长 (聚合函数默认 mean, 也可先调用 Func)。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址