使用Golang訪問Apache IoTTDB時序數(shù)據(jù)庫:環(huán)境搭建 + 連接池 + 全接口實戰(zhàn)
IoTDB Go 原生 API 提供 Session 與 SessionPool 兩種交互方式。由于 Session 非線程安全,高并發(fā)場景強烈推薦使用 SessionPool,能高效管理連接、提升系統(tǒng)性能與資源利用率。
本文從環(huán)境準(zhǔn)備、核心流程、完整示例到全量接口,帶你快速用 Go 接入 IoTDB 時序數(shù)據(jù)庫。
1. 環(huán)境準(zhǔn)備
1.1 前置依賴
- Golang ≥ 1.13
- make ≥ 3.0
- curl ≥ 7.1.1
- Thrift 0.15.0
- 系統(tǒng):Linux/Mac/Windows+bash(WSL/cygwin/Git Bash)
1.2 安裝方法
使用 Go Mod(推薦)
# 啟用 Go Modules export GO111MODULE=on # 配置代理 export GOPROXY=https://goproxy.io # 創(chuàng)建項目目錄 mkdir session_example && cd session_example # 下載官方示例 curl -o session_example.go -L https://github.com/apache/iotdb-client-go/raw/main/example/session_example.go # 初始化并下載依賴 go mod init session_example go mod tidy # 運行 go run session_example.go
使用 GOPATH
# 安裝 thrift go get github.com/apache/thrift@0.13.0 # 創(chuàng)建目錄 mkdir -p $GOPATH/src/iotdb-client-go-example/session_example cd $GOPATH/src/iotdb-client-go-example/session_example # 下載示例 curl -o session_example.go -L https://github.com/apache/iotdb-client-go/raw/main/example/session_example.go # 初始化依賴 go mod init go mod tidy # 運行 go run session_example.go
?? 重要提醒:禁止高版本客戶端連接低版本服務(wù)端,否則會出現(xiàn)連接異常、數(shù)據(jù)寫入失敗等問題。
2. 核心開發(fā)步驟
使用 Go 操作 IoTDB 只需要三步:
- 創(chuàng)建 SessionPool 連接池實例
- 從連接池獲取 Session 執(zhí)行操作,用完歸還
- 程序結(jié)束關(guān)閉連接池釋放資源
2.1 創(chuàng)建連接池實例
單節(jié)點模式
config := &client.PoolConfig{
Host: "127.0.0.1",
Port: "6667",
UserName: "root",
Password: "root",
}
// 創(chuàng)建連接池:最大連接數(shù)3、連接超時60s、獲取等待60s、關(guān)閉壓縮
sessionPool = client.NewSessionPool(config, 3, 60000, 60000, false)
defer sessionPool.Close()
分布式/雙活模式
config := &client.PoolConfig{
UserName: "root",
Password: "root",
NodeUrls: strings.Split("127.0.0.1:6667,127.0.0.1:6668", ","),
}
sessionPool = client.NewSessionPool(config, 3, 60000, 60000, false)
defer sessionPool.Close()
2.2 數(shù)據(jù)庫操作
數(shù)據(jù)寫入(Tablet 推薦)
session, err := sessionPool.GetSession() defer sessionPool.PutBack(session) status, err := session.InsertTablet(tablet, false) tablet.Reset()
數(shù)據(jù)查詢
var timeout int64 = 1000 session, err := sessionPool.GetSession() defer sessionPool.PutBack(session) sessionDataSet, err := session.ExecuteQueryStatement(sql, &timeout) defer sessionDataSet.Close()
2.3 完整可運行示例
package main
import (
"flag"
"fmt"
"log"
"math/rand"
"strings"
"time"
"github.com/apache/iotdb-client-go/v2/client"
"github.com/apache/iotdb-client-go/v2/common"
)
var (
host string
port string
user string
password string
sessionPool client.SessionPool
)
func main() {
flag.StringVar(&host, "host", "127.0.0.1", "--host=192.168.1.100")
flag.StringVar(&port, "port", "6667", "--port=6667")
flag.StringVar(&user, "user", "root", "--user=root")
flag.StringVar(&password, "password", "root", "--password=root")
flag.Parse()
// 1. 創(chuàng)建連接池
config := &client.PoolConfig{Host: host, Port: port, UserName: user, Password: password}
sessionPool = client.NewSessionPool(config, 3, 60000, 60000, false)
defer sessionPool.Close()
// 2. 元數(shù)據(jù)操作
setStorageGroup("root.sg1")
createTimeseries("root.sg1.dev1.temperature")
// 3. 寫入數(shù)據(jù)
insertTablet()
// 4. 查詢數(shù)據(jù)
executeQueryStatement("select temperature from root.sg1.dev1")
// 5. 清理資源
deleteTimeseries("root.sg1.dev1.temperature")
deleteStorageGroup("root.sg1")
}
// 設(shè)置存儲組
func setStorageGroup(sg string) {
session, err := sessionPool.GetSession()
defer sessionPool.PutBack(session)
if err == nil {
session.SetStorageGroup(sg)
}
}
// 創(chuàng)建時間序列
func createTimeseries(path string) {
session, err := sessionPool.GetSession()
defer sessionPool.PutBack(session)
if err == nil {
checkError(session.CreateTimeseries(path, client.FLOAT, client.PLAIN, client.SNAPPY, nil, nil))
}
}
// 插入Tablet
func insertTablet() {
session, err := sessionPool.GetSession()
defer sessionPool.PutBack(session)
if err == nil {
tablet, err := client.NewTablet("root.sg1.dev1", []*client.MeasurementSchema{{Measurement: "temperature", DataType: client.FLOAT}}, 12)
if err != nil {
log.Fatal(err)
}
ts := time.Now().UTC().UnixNano() / 1000000
for row := 0; row < 12; row++ {
ts++
tablet.SetTimestamp(ts, row)
tablet.SetValueAt(rand.Float32(), 0, row)
tablet.RowSize++
}
status, err := session.InsertTablet(tablet, false)
tablet.Reset()
checkError(status, err)
}
}
// 查詢語句
func executeQueryStatement(sql string) {
var timeout int64 = 1000
session, err := sessionPool.GetSession()
defer sessionPool.PutBack(session)
if err != nil {
log.Print(err)
return
}
sds, err := session.ExecuteQueryStatement(sql, &timeout)
if err == nil {
defer sds.Close()
cols := sds.GetColumnNames()
for _, c := range cols { fmt.Printf("%s\t", c) }
fmt.Println()
for next, _ := sds.Next(); next; next, _ = sds.Next() {
for _, c := range cols {
if null, _ := sds.IsNull(c); null {
fmt.Print("null\t")
} else {
v, _ := sds.GetString(c)
fmt.Printf("%s\t", v)
}
}
fmt.Println()
}
}
}
// 刪除時序
func deleteTimeseries(paths ...string) {
session, err := sessionPool.GetSession()
defer sessionPool.PutBack(session)
if err == nil { checkError(session.DeleteTimeseries(paths)) }
}
// 刪除存儲組
func deleteStorageGroup(sg string) {
session, err := sessionPool.GetSession()
defer sessionPool.PutBack(session)
if err == nil { checkError(session.DeleteStorageGroup(sg)) }
}
// 錯誤檢查
func checkError(status *common.TSStatus, err error) {
if err != nil { log.Fatal(err) }
if status != nil {
if e := client.VerifySuccess(status); e != nil { log.Println(e) }
}
}
3. 全量接口說明
3.1 SessionPool 管理接口
| 接口 | 功能 | 說明 |
|---|---|---|
| NewSessionPool | 創(chuàng)建連接池 | 支持單節(jié)點/集群 |
| GetSession | 獲取會話 | 必須與 PutBack 配對 |
| PutBack | 歸還會話 | 用完立即歸還 |
| Close | 關(guān)閉連接池 | 程序退出前調(diào)用 |
3.2 數(shù)據(jù)寫入接口
支持 Record/Tablet,支持對齊/非對齊,批量寫入優(yōu)先使用 Tablet:
- InsertRecord / InsertRecords
- InsertAlignedRecord / InsertAlignedRecords
- InsertTablet / InsertTablets
- InsertAlignedTablet / InsertAlignedTablets
3.3 SQL 與查詢接口
- ExecuteQueryStatement:執(zhí)行查詢
- ExecuteNonQueryStatement:執(zhí)行非查詢SQL
- ExecuteRawDataQuery:原始數(shù)據(jù)查詢
- ExecuteAggregationQuery:聚合查詢
3.4 元數(shù)據(jù)操作接口
- SetStorageGroup / DeleteStorageGroup
- CreateTimeseries / CreateAlignedTimeseries
- DeleteTimeseries / DeleteData
- SetTimeZone / GetTimeZone
3.5 PoolConfig 關(guān)鍵配置
- Host/Port:單節(jié)點地址
- NodeUrls:集群地址列表
- UserName/Password:認(rèn)證信息
- FetchSize:結(jié)果集獲取條數(shù)
- TimeZone:會話時區(qū)
附:IoTDB的各大版本
?? Apache IoTDB 是一款工業(yè)物聯(lián)網(wǎng)時序數(shù)據(jù)庫管理系統(tǒng),采用端邊云協(xié)同的輕量化架構(gòu),支持一體化的物聯(lián)網(wǎng)時序數(shù)據(jù)收集、存儲、管理與分析 ,具有多協(xié)議兼容、超高壓縮比、高通量讀寫、工業(yè)級穩(wěn)定、極簡運維等特點。
| 版本 | IoTDB 二進制包 | IoTDB 源代碼 | 發(fā)布說明 |
|---|---|---|---|
| 2.0.5 | - All-in-one - AINode - SHA512 - ASC | - 源代碼 - SHA512 - ASC | release notes |
| 1.3.5 | - All-in-one - AINode - SHA512 - ASC | - 源代碼 - SHA512 - ASC | release notes |
| 0.13.4 | - All-in-one - Grafana 連接器 - Grafana 插件 - SHA512 - ASC | - 源代碼 - SHA512 - ASC | release notes |
? 目前最新版本為2.0.7,去獲取:https://archive.apache.org/dist/iotdb/
文章總結(jié)
本文全面講解 Apache IoTDB Go 原生接口的使用方法,先明確 Golang、Thrift 等依賴要求,提供 Go Mod 與 GOPATH 兩種安裝方式。重點介紹 SessionPool 連接池 的創(chuàng)建、使用與歸還規(guī)范,給出包含創(chuàng)建存儲組、時序、數(shù)據(jù)寫入、查詢、刪除的完整可運行代碼。同時分類整理連接池管理、數(shù)據(jù)寫入、SQL查詢、元數(shù)據(jù)操作等全量接口,清晰說明配置項與使用注意事項。幫助 Go 開發(fā)者快速完成 IoTDB 集成,實現(xiàn)高并發(fā)、高性能的時序數(shù)據(jù)開發(fā)與生產(chǎn)落地。
到此這篇關(guān)于使用Golang訪問Apache IoTTDB時序數(shù)據(jù)庫:環(huán)境搭建 + 連接池 + 全接口實戰(zhàn)的文章就介紹到這了,更多相關(guān)Golang訪問Apache IoTTDB教程內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go語言結(jié)合Redis實現(xiàn)用戶登錄次數(shù)限制功能
Redis 的高性能和天然的過期機制,非常適合實現(xiàn)這種登錄限流功能,本文將通過 Go + Redis 實現(xiàn)一個 用戶登錄次數(shù)限制 示例,感興趣的小伙伴可以了解下2025-09-09
Golang利用image包進行圖像基礎(chǔ)處理的深度指南
在?Go?語言中,圖像處理主要依賴標(biāo)準(zhǔn)庫中的?image?包,它為開發(fā)者提供了一套統(tǒng)一的圖像模型和接口,用于處理圖片數(shù)據(jù),下面小編就和大家詳細介紹一下吧2026-03-03
詳解Golang time包中的結(jié)構(gòu)體time.Time
在日常開發(fā)過程中,會頻繁遇到對時間進行操作的場景,使用 Golang 中的 time 包可以很方便地實現(xiàn)對時間的相關(guān)操作,本文先講解一下 time 包中的結(jié)構(gòu)體 time.Time,需要的朋友可以參考下2023-07-07
Go 代碼規(guī)范錯誤處理示例經(jīng)驗總結(jié)
這篇文章主要為大家介紹了Go 代碼規(guī)范錯誤處理示例實戰(zhàn)經(jīng)驗總結(jié),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08

