使用InfluxDB API写入数据
使用HTTP请求将数据写入InfluxDB,通过InfluxDB API /api/v2/write 终端。
使用POST请求方法,并在请求中包含以下内容:
| 需求 | 包含到 |
|---|---|
| 组织 | 在你的请求URL中使用org查询参数。 |
| 桶 | 在您的请求URL中使用 bucket 查询参数。 |
| 时间戳精度 | 在您的请求URL中使用 precision 查询参数。默认值是 ns。 |
| API令牌 | 使用Authorization: Token YOUR_API_TOKEN头部。 |
| 行协议 | 作为纯文本传递在你的请求体中。 |
发送写请求
示例中的URL取决于您InfluxDB 2.7 实例的版本和位置。 自定义示例中的URL
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-Type: text/plain; charset=utf-8" \
--header "Accept: application/json" \
--data-binary '
airSensors,sensor_id=TLM0201 temperature=73.97038159354763,humidity=35.23103248356096,co=0.48445310567793615 1630424257000000000
airSensors,sensor_id=TLM0202 temperature=75.30007505999716,humidity=35.651929918691714,co=0.5141876544505826 1630424257000000000
'
'use strict'
/** @module write
* Writes a data point to InfluxDB using the Javascript client library with Node.js.
**/
import { InfluxDB, Point } from '@influxdata/influxdb-client'
/** Environment variables **/
const url = process.env.INFLUX_URL
const token = process.env.INFLUX_TOKEN
const org = process.env.INFLUX_ORG
const bucket = process.env.INFLUX_BUCKET
/**
* Instantiate the InfluxDB client
* with a configuration object.
**/
const influxDB = new InfluxDB({ url, token })
/**
* Create a write client from the getWriteApi method.
* Provide your `org` and `bucket`.
**/
const writeApi = influxDB.getWriteApi(org, bucket)
/**
* Apply default tags to all points.
**/
writeApi.useDefaultTags({ region: 'west' })
/**
* Create a point and write it to the buffer.
**/
const point1 = new Point('temperature')
.tag('sensor_id', 'TLM01')
.floatField('value', 24.0)
console.log(` ${point1}`)
writeApi.writePoint(point1)
/**
* Flush pending writes and close writeApi.
**/
writeApi.close().then(() => {
console.log('WRITE FINISHED')
})
使用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
有关 InfluxDB API 响应代码 的信息,请参阅 InfluxDB API 写入文档。