下面我将为您详细讲解Java使用InfluxDB数据库的详细代码。
1. InfluxDB简介
InfluxDB是一种开源的分布式时序数据库,广泛应用于监控、IoT、实时分析等领域。它具有以下特点:
- 高效的写入和查询
- 支持SQL查询语言
- 支持数据压缩和自动删除
- 支持分布式架构
2. 安装InfluxDB
在使用InfluxDB前,需要先下载并安装InfluxDB。官网提供了多种安装方式,这里以Docker方式为例。
# 先安装Docker
sudo apt install docker.io
# 拉取InfluxDB镜像
sudo docker pull influxdb
# 启动InfluxDB容器
sudo docker run -p 8086:8086 -v influxdb:/var/lib/influxdb influxdb
3. 连接InfluxDB
Java中连接InfluxDB的方式有多种,这里介绍使用Java API方式连接。需要先在Maven中添加InfluxDB Java API的依赖:
<dependency>
<groupId>org.influxdb</groupId>
<artifactId>influxdb-java</artifactId>
<version>2.16</version>
</dependency>
在连接InfluxDB前,需要定义InfluxDB连接的配置文件:
InfluxDBConfig influxDBConfig = InfluxDBConfig.builder()
.url("http://localhost:8086")
.username("admin")
.password("admin")
.database("test")
.build();
根据配置文件创建InfluxDB实例:
InfluxDB influxDB = InfluxDBFactory.connect(influxDBConfig);
4. 插入数据
插入数据需要先定义数据模型。以一个传感器温度数据为例:
@Data
public class SensorData {
private String sensorId;
private Timestamp timestamp;
private Double temperature;
}
使用Java API方式插入数据:
SensorData sensorData = new SensorData();
sensorData.setSensorId("s1");
sensorData.setTimestamp(new Timestamp(System.currentTimeMillis()));
sensorData.setTemperature(22.5);
Point point = Point.measurement("temperature")
.time(sensorData.getTimestamp().getTime(), TimeUnit.MILLISECONDS)
.tag("sensorId", sensorData.getSensorId())
.addField("temperature", sensorData.getTemperature())
.build();
influxDB.write(point);
5. 查询数据
查询数据需要先定义查询语句。以查询传感器s1最近20条温度数据为例:
String query = String.format("SELECT temperature FROM temperature WHERE sensorId='s1' ORDER BY time DESC LIMIT 20");
使用Java API方式查询数据:
QueryResult queryResult = influxDB.query(new Query(query, database));
List<QueryResult.Result> results = queryResult.getResults();
if (results != null && !results.isEmpty()) {
QueryResult.Result result = results.get(0);
if (result.getSeries() != null && !result.getSeries().isEmpty()) {
QueryResult.Series series = result.getSeries().get(0);
List<String> columns = series.getColumns();
List<List<Object>> values = series.getValues();
// 处理查询结果
for (List<Object> value : values) {
Double temperature = Double.parseDouble(value.get(columns.indexOf("temperature")).toString());
System.out.println(temperature);
}
}
}
6. 完整代码示例
以下是完整的Java使用InfluxDB的代码示例。
import lombok.Data;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.InfluxDBIOException;
import org.influxdb.InfluxDBIOException.InfluxDBIOExceptionBuilder;
import org.influxdb.InfluxDBResponseException;
import org.influxdb.dto.Point;
import org.influxdb.dtO.Point.Builder;
import org.influxdb.dto.QueryResult;
import java.sql.Timestamp;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class InfluxDBExample {
public static void main(String[] args) {
// 数据库连接配置
InfluxDBConfig influxDBConfig = InfluxDBConfig.builder()
.url("http://localhost:8086")
.username("admin")
.password("admin")
.database("test")
.build();
// 创建InfluxDB实例
InfluxDB influxDB = InfluxDBFactory.connect(influxDBConfig);
// 插入数据
SensorData sensorData = new SensorData();
sensorData.setSensorId("s1");
sensorData.setTimestamp(new Timestamp(System.currentTimeMillis()));
sensorData.setTemperature(22.5);
Point point = Point.measurement("temperature")
.time(sensorData.getTimestamp().getTime(), TimeUnit.MILLISECONDS)
.tag("sensorId", sensorData.getSensorId())
.addField("temperature", sensorData.getTemperature())
.build();
influxDB.write(point);
// 查询数据
String query = String.format("SELECT temperature FROM temperature WHERE sensorId='s1' ORDER BY time DESC LIMIT 20");
QueryResult queryResult = influxDB.query(new Query(query, database));
List<QueryResult.Result> results = queryResult.getResults();
if (results != null && !results.isEmpty()) {
QueryResult.Result result = results.get(0);
if (result.getSeries() != null && !result.getSeries().isEmpty()) {
QueryResult.Series series = result.getSeries().get(0);
List<String> columns = series.getColumns();
List<List<Object>> values = series.getValues();
// 处理查询结果
for (List<Object> value : values) {
Double temperature = Double.parseDouble(value.get(columns.indexOf("temperature")).toString());
System.out.println(temperature);
}
}
}
// 关闭InfluxDB连接
influxDB.close();
}
@Data
public static class SensorData {
private String sensorId;
private Timestamp timestamp;
private Double temperature;
}
@Data
public static class InfluxDBConfig {
private String url;
private String username;
private String password;
private String database;
public static Builder builder() {
return new Builder();
}
public static class Builder {
private InfluxDBConfig config = new InfluxDBConfig();
public Builder url(String url) {
config.setUrl(url);
return this;
}
public Builder username(String username) {
config.setUsername(username);
return this;
}
public Builder password(String password) {
config.setPassword(password);
return this;
}
public Builder database(String database) {
config.setDatabase(database);
return this;
}
public InfluxDBConfig build() {
return config;
}
}
}
}
以上是Java使用InfluxDB的完整攻略,希望能对您有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java使用influxDB数据库的详细代码 - Python技术站