InfluxDB Rust 客户端使用教程
1. 项目的目录结构及介绍
InfluxDB Rust 客户端项目的目录结构如下:
influxdb-rust/
├── Cargo.toml
├── src/
│ ├── client.rs
│ ├── error.rs
│ ├── lib.rs
│ ├── query.rs
│ ├── types.rs
│ └── write.rs
├── examples/
│ ├── basic_write.rs
│ ├── basic_query.rs
│ └── ...
├── tests/
│ ├── integration_tests.rs
│ └── ...
└── README.md
目录结构介绍
Cargo.toml
: 项目的依赖和元数据配置文件。src/
: 包含项目的源代码文件。client.rs
: 客户端实现。error.rs
: 错误处理模块。lib.rs
: 库的入口文件。query.rs
: 查询相关功能。types.rs
: 数据类型定义。write.rs
: 写入相关功能。
examples/
: 包含示例代码,展示如何使用该库。tests/
: 包含集成测试代码。README.md
: 项目说明文档。
2. 项目的启动文件介绍
项目的启动文件通常是指示例代码中的文件,用于展示如何启动和使用 InfluxDB Rust 客户端。以下是 examples/basic_write.rs
的示例代码:
use influxdb::Client;
use influxdb::InfluxDbWriteable;
use chrono::Utc;
#[derive(InfluxDbWriteable)]
struct WeatherReading {
time: DateTime<Utc>,
humidity: i32,
#[influxdb(tag)] wind_direction: String,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Connect to db `test` on `http://localhost:8086`
let client = Client::new("http://localhost:8086", "test");
// Let's write some data into a measurement called `weather`
let weather_readings = vec![
WeatherReading {
time: Utc::now(),
humidity: 30,
wind_direction: String::from("north"),
},
WeatherReading {
time: Utc::now(),
humidity: 40,
wind_direction: String::from("west"),
},
];
client.query(&weather_readings.into_iter().map(|reading| reading.into_query("weather")).collect::<Vec<_>>()).await?;
Ok(())
}
启动文件介绍
examples/basic_write.rs
: 展示如何连接到 InfluxDB 并写入数据。examples/basic_query.rs
: 展示如何从 InfluxDB 查询数据。
3. 项目的配置文件介绍
项目的配置文件主要是 Cargo.toml
,它包含了项目的依赖、版本信息和其他元数据。以下是 Cargo.toml
的部分内容:
[package]
name = "influxdb-rust"
version = "0.7.2"
authors = ["Gero Gerke <gero.gerke@gmail.com>", "msrd0 <contact@msrd0.de>", "and contributors"]
edition = "2018"
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.11", features = ["json"] }
chrono = { version = "0.4", features = ["serde"] }
[features]
default = ["derive", "serde", "reqwest-client"]
derive = []
serde = []
reqwest-client = []
配置文件介绍
[package]
: 定义了包的名称、版本和作者等信息。[dependencies]
: 列出了项目依赖的库及其版本。[features]
: 定义了项目的特性,如 `