Assume that you have installed JDK on your local system. If not, you can go to the Oracle site to download it and follow the instructions for installation. Once the installation is successful, type java -version. You should see the current version of JDK as shown in the following URL:
http://www.oracle.com/technetwork/java/javase/downloads/index.html.
- First, we need to create a maven project and define Maven pom.xml with the following dependency library and add InfluxDB-related dependencies:
<dependencies>
<dependency>
<groupId>org.InfluxDB</groupId>
<artifactId>InfluxDB-java</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.9.1</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-moshi</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
- Write a Java program:
publicclass InfluxDBApiTest {
publicstaticvoid main(String[] args) throws Exception {
InfluxDB InfluxDB = InfluxDBFactory.connect("http://yourInfluxDBInstanceIPAddress:8086", "root", "root");
String dbName = "testdb";
InfluxDB.createDatabase(dbName);
InfluxDB.setDatabase(dbName);
Point point1 = Point.measurement("apachelog_java").time(1511361120000000000L, TimeUnit.NANOSECONDS)
.addField("http", "GET /cgi-bin/try/ HTTP/1.0").addField("status", 200).addField("duration", 3395)
.addField("ip", "192.168.2.20").build();
Point point2 = Point.measurement("apachelog_java").time(1511361180000000000L, TimeUnit.NANOSECONDS)
.addField("http", "GET / HTTP/1.0").addField("status", 200).addField("duration", 2216)
.addField("ip", "127.0.0.1").build();
InfluxDB.write(point1);
InfluxDB.write(point2);
Query query = new Query("SELECT * FROM apachelog_java", dbName);
InfluxDB.query(query, 20, queryResult -> System.out.println(queryResult));
}
}
- After running this program, it will print out two records, which are written to the new appachelog_java measurement:
QueryResult [results=[Result [series=[Series [name=apachelog_java, tags=null, columns=[time, duration, http, ip, status], values=[[2017-11-22T14:32:00Z, 3395.0, GET /cgi-bin/try/ HTTP/1.0, 192.168.2.20, 200.0], [2017-11-22T14:33:00Z, 2216.0, GET / HTTP/1.0, 127.0.0.1, 200.0]]]], error=null]], error=null]