更多文章:
如何使用Java操作InfluxDB
要使用Java操作InfluxDB,您需要添加以下Maven依赖项:
<dependency>
<groupId>org.influxdb</groupId>
<artifactId>influxdb-java</artifactId>
<version>2.17</version>
</dependency>
以下是Java实现InfluxDB的数据增删改查的样例代码:
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import java.util.concurrent.TimeUnit;
public class InfluxDBOperations {
private static final String INFLUXDB_URL = “http://localhost:8086”;
private static final String INFLUXDB_USERNAME = “username”;
private static final String INFLUXDB_PASSWORD = “password”;
private static final String DATABASE_NAME = “mydb”;
public static void main(String[] args) {
// 连接到InfluxDB实例
InfluxDB influxDB = InfluxDBFactory.connect(INFLUXDB_URL, INFLUXDB_USERNAME, INFLUXDB_PASSWORD);
// 创建数据库(如果不存在)
influxDB.createDatabase(DATABASE_NAME);
// 选择数据库
influxDB.setDatabase(DATABASE_NAME);
// 创建点数据
Point point1 = Point.measurement(“cpu”)
.time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
.addField(“value”, 80)
.addField(“host”, “server1”)
.build();
Point point2 = Point.measurement(“cpu”)
.time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
.addField(“value”, 65)
.addField(“host”, “server2”)
.build();
// 写入单个点数据
influxDB.write(point1);
// 批量写入点数据
BatchPoints batchPoints = BatchPoints.database(DATABASE_NAME)
.point(point2)
.build();
influxDB.write(batchPoints);
// 查询数据
Query query = new Query(“SELECT value FROM cpu”, DATABASE_NAME);
QueryResult queryResult = influxDB.query(query);
System.out.println(queryResult);
// 删除数据
Query deleteQuery = new Query(“DELETE FROM cpu WHERE host = ‘server1′”, DATABASE_NAME);
influxDB.query(deleteQuery);
// 关闭连接
influxDB.close();
}
}
更多文章:
如何使用Java操作InfluxDB