优化写入 InfluxDB
使用以下技巧来优化性能和系统开销,以便将数据写入 InfluxDB。
以下工具写入 InfluxDB,默认情况下采用大多数写入优化
批量写入
批量写入数据,以最大限度地减少将数据写入 InfluxDB 时的网络开销。
最佳批量大小为 5000 行 Line Protocol。
按键对标签进行排序
在将数据点写入 InfluxDB 之前,请按字典顺序按键对标签进行排序。验证排序结果是否与 Go bytes.Compare
函数的结果匹配。
# Line protocol example with unsorted tags
measurement,tagC=therefore,tagE=am,tagA=i,tagD=i,tagB=think fieldKey=fieldValue 1562020262
# Optimized line protocol example with tags sorted by key
measurement,tagA=i,tagB=think,tagC=therefore,tagD=i,tagE=am fieldKey=fieldValue 1562020262
使用尽可能粗略的时间精度
默认情况下,InfluxDB 以纳秒精度写入数据。但是,如果你的数据不是以纳秒为单位收集的,则无需以该精度写入。为了获得更好的性能,请为时间戳使用尽可能粗略的精度。
在写入 InfluxDB时指定时间戳精度。
使用 gzip 压缩
使用 gzip 压缩来加快写入 InfluxDB 的速度并减少网络带宽。基准测试表明,数据压缩后速度最多可提高 5 倍。
在 Telegraf 中启用 gzip 压缩
在你的 telegraf.conf
中的 influxdb_v2
输出插件配置中,将 content_encoding
选项设置为 gzip
[[outputs.influxdb_v2]]
urls = ["http://localhost:8086"]
# ...
content_encoding = "gzip"
在 InfluxDB 客户端库中启用 gzip 压缩
每个 InfluxDB 客户端库都提供了压缩写入请求的选项,或者默认强制压缩。启用压缩的方法因库而异。有关具体说明,请参阅 InfluxDB 客户端库文档。
将 gzip 压缩与 InfluxDB API 一起使用
当使用 InfluxDB API /api/v2/write
端点写入数据时,请使用 gzip
压缩数据并将 Content-Encoding
标头设置为 gzip
。
echo "airSensors,sensor_id=TLM0201 temperature=73.97038159354763,humidity=35.23103248356096,co=0.48445310567793615 1630525358
airSensors,sensor_id=TLM0202 temperature=75.30007505999716,humidity=35.651929918691714,co=0.5141876544505826 1630525358" | gzip > air-sensors.gzip
curl --request POST \
"http://localhost:8086/api/v2/write?org=YOUR_ORG&bucket=YOUR_BUCKET&precision=ns" \
--header "Authorization: Token YOUR_API_TOKEN" \
--header "Content-Encoding: gzip" \
--header "Content-Type: text/plain; charset=utf-8" \
--header "Accept: application/json" \
--data-binary @air-sensors.gzip
使用 NTP 同步主机
使用网络时间协议 (NTP) 同步主机之间的时间。如果 Line Protocol 中未包含时间戳,则 InfluxDB 使用其主机的本地时间(UTC)为每个点分配时间戳。如果主机的时钟未与 NTP 同步,则时间戳可能不准确。
在一个请求中写入多个数据点
要在一个请求中写入多行,则 Line Protocol 的每一行必须用换行符 (\n
) 分隔。
速率限制
使用 influx write
--rate-limit
标志来控制写入速率。使用以下字符串格式之一来指定速率限制
COUNT(B|kB|MB)
,或COUNT(B|kB|MB)/TIME(s|sec|m|min)
其中 COUNT
是十进制数,TIME
是正整数。值中的空格将被忽略。例如:“5MB / 5min”也可以表示为 17476.266666667Bs
、1MB/1min
、1MB/min
、1MBmin
或 1MBm
。如果速率限制格式无效,influx write
将打印出格式和精确的正则表达式。 --rate-limit
标志也可以与 influx write dryrun
一起使用。
默认情况下,InfluxDB Cloud 中的免费层速率限制为 1MB/min
。
此页面是否对您有帮助?
感谢您的反馈!