influxdb-client-java

Java - 图1

CircleCI codecov License Maven Central Maven Site GitHub issues GitHub pull requests Slack Status

This repository contains the Java client library for use with InfluxDB 2.x and Flux. Currently, Java, Reactive, Kotlin and Scala clients are implemented. InfluxDB 3.x users should instead use the lightweight v3 client library. InfluxDB 1.x users should use the v1 client library.

For ease of migration and a consistent query and write experience, v2 users should consider using InfluxQL and the v1 client library.

Documentation

Java - 图10

This section contains links to the client library documentation.

Features

Java - 图11

  • InfluxDB 2.x client
    • Querying data using the Flux language
    • Querying data using the InfluxQL
    • Writing data using
    • InfluxDB 2.x Management API client for managing
      • sources, buckets
      • tasks
      • authorizations
      • health check
  • Supports querying using the Flux language over the InfluxDB 1.7+ REST API (/api/v2/query endpoint)

Clients

Java - 图12

The Java, Reactive, OSGi, Kotlin and Scala clients are implemented for the InfluxDB 2.x:

ClientDescriptionDocumentationCompatibility
javaThe reference Java client that allows query, write and InfluxDB 2.x management.javadoc, readme2.x
reactiveThe reference RxJava client for the InfluxDB 2.x that allows query and write in a reactive way.javadoc, readme2.x
kotlinThe reference Kotlin client that allows query and write for the InfluxDB 2.x by Kotlin Channel and Flow coroutines.KDoc, readme2.x
scalaThe reference Scala client that allows query and write for the InfluxDB 2.x by Pekko Streams.Scaladoc, readme2.x
osgiThe reference OSGi (R6) client embedding Java and reactive clients and providing standard features (declarative services, configuration, event processing) for the InfluxDB 2.x.javadoc, readme2.x
karafThe Apache Karaf feature definition for the InfluxDB 2.x.readme2.x

There is also possibility to use the Flux language over the InfluxDB 1.7+ provided by:

ClientDescriptionDocumentationCompatibility
fluxThe reference Java client that allows you to perform Flux queries against InfluxDB 1.7+.javadoc, readme1.7+

The last useful part is flux-dsl that helps construct Flux query by Query builder pattern:

  1. Flux flux = Flux
  2. .from("telegraf")
  3. .window(15L, ChronoUnit.MINUTES, 20L, ChronoUnit.SECONDS)
  4. .sum();
ModuleDescriptionDocumentationCompatibility
flux-dslA Java query builder for the Flux languagejavadoc, readme1.7+, 2.x

How To Use

Java - 图13

This clients are hosted in Maven central Repository.

If you want to use it with the Maven, you have to add only the dependency on the artifact.

Writes and Queries in InfluxDB 2.x

Java - 图14

The following example demonstrates how to write data to InfluxDB 2.x and read them back using the Flux language.

Installation

Java - 图15

Download the latest version:

Maven dependency:

Java - 图16

  1. <dependency>
  2. <groupId>com.influxdb</groupId>
  3. <artifactId>influxdb-client-java</artifactId>
  4. <version>7.2.0</version>
  5. </dependency>
Or when using Gradle:

Java - 图17

  1. dependencies {
  2. implementation "com.influxdb:influxdb-client-java:7.2.0"
  3. }
  1. package example;
  2. import java.time.Instant;
  3. import java.util.List;
  4. import com.influxdb.annotations.Column;
  5. import com.influxdb.annotations.Measurement;
  6. import com.influxdb.client.InfluxDBClient;
  7. import com.influxdb.client.InfluxDBClientFactory;
  8. import com.influxdb.client.QueryApi;
  9. import com.influxdb.client.WriteApiBlocking;
  10. import com.influxdb.client.domain.WritePrecision;
  11. import com.influxdb.client.write.Point;
  12. import com.influxdb.query.FluxRecord;
  13. import com.influxdb.query.FluxTable;
  14. public class InfluxDB2Example {
  15. private static char[] token = "my-token".toCharArray();
  16. private static String org = "my-org";
  17. private static String bucket = "my-bucket";
  18. public static void main(final String[] args) {
  19. InfluxDBClient influxDBClient = InfluxDBClientFactory.create("http://localhost:8086", token, org, bucket);
  20. //
  21. // Write data
  22. //
  23. WriteApiBlocking writeApi = influxDBClient.getWriteApiBlocking();
  24. //
  25. // Write by Data Point
  26. //
  27. Point point = Point.measurement("temperature")
  28. .addTag("location", "west")
  29. .addField("value", 55D)
  30. .time(Instant.now().toEpochMilli(), WritePrecision.MS);
  31. writeApi.writePoint(point);
  32. //
  33. // Write by LineProtocol
  34. //
  35. writeApi.writeRecord(WritePrecision.NS, "temperature,location=north value=60.0");
  36. //
  37. // Write by POJO
  38. //
  39. Temperature temperature = new Temperature();
  40. temperature.location = "south";
  41. temperature.value = 62D;
  42. temperature.time = Instant.now();
  43. writeApi.writeMeasurement( WritePrecision.NS, temperature);
  44. //
  45. // Query data
  46. //
  47. String flux = "from(bucket:\"my-bucket\") |> range(start: 0)";
  48. QueryApi queryApi = influxDBClient.getQueryApi();
  49. List<FluxTable> tables = queryApi.query(flux);
  50. for (FluxTable fluxTable : tables) {
  51. List<FluxRecord> records = fluxTable.getRecords();
  52. for (FluxRecord fluxRecord : records) {
  53. System.out.println(fluxRecord.getTime() + ": " + fluxRecord.getValueByKey("_value"));
  54. }
  55. }
  56. influxDBClient.close();
  57. }
  58. @Measurement(name = "temperature")
  59. private static class Temperature {
  60. @Column(tag = true)
  61. String location;
  62. @Column
  63. Double value;
  64. @Column(timestamp = true)
  65. Instant time;
  66. }
  67. }

Use Management API to create a new Bucket in InfluxDB 2.x

Java - 图18

The following example demonstrates how to use a InfluxDB 2.x Management API. For further information see client documentation.

Installation

Java - 图19

Download the latest version:

Maven dependency:

Java - 图20

  1. <dependency>
  2. <groupId>com.influxdb</groupId>
  3. <artifactId>influxdb-client-java</artifactId>
  4. <version>7.2.0</version>
  5. </dependency>
Or when using Gradle:

Java - 图21

  1. dependencies {
  2. implementation "com.influxdb:influxdb-client-java:7.2.0"
  3. }
  1. package example;
  2. import java.util.Arrays;
  3. import com.influxdb.client.InfluxDBClient;
  4. import com.influxdb.client.InfluxDBClientFactory;
  5. import com.influxdb.client.domain.Authorization;
  6. import com.influxdb.client.domain.Bucket;
  7. import com.influxdb.client.domain.Permission;
  8. import com.influxdb.client.domain.PermissionResource;
  9. import com.influxdb.client.domain.BucketRetentionRules;
  10. public class InfluxDB2ManagementExample {
  11. private static char[] token = "my-token".toCharArray();
  12. public static void main(final String[] args) {
  13. InfluxDBClient influxDBClient = InfluxDBClientFactory.create("http://localhost:8086", token);
  14. //
  15. // Create bucket "iot_bucket" with data retention set to 3,600 seconds
  16. //
  17. BucketRetentionRules retention = new BucketRetentionRules();
  18. retention.setEverySeconds(3600);
  19. Bucket bucket = influxDBClient.getBucketsApi().createBucket("iot-bucket", retention, "12bdc4164c2e8141");
  20. //
  21. // Create access token to "iot_bucket"
  22. //
  23. PermissionResource resource = new PermissionResource();
  24. resource.setId(bucket.getId());
  25. resource.setOrgID("12bdc4164c2e8141");
  26. resource.setType(PermissionResource.TYPE_BUCKETS);
  27. // Read permission
  28. Permission read = new Permission();
  29. read.setResource(resource);
  30. read.setAction(Permission.ActionEnum.READ);
  31. // Write permission
  32. Permission write = new Permission();
  33. write.setResource(resource);
  34. write.setAction(Permission.ActionEnum.WRITE);
  35. Authorization authorization = influxDBClient.getAuthorizationsApi()
  36. .createAuthorization("12bdc4164c2e8141", Arrays.asList(read, write));
  37. //
  38. // Created token that can be use for writes to "iot_bucket"
  39. //
  40. String token = authorization.getToken();
  41. System.out.println("Token: " + token);
  42. influxDBClient.close();
  43. }
  44. }

InfluxDB 1.8 API compatibility

Java - 图22

InfluxDB 1.8.0 introduced forward compatibility APIs for InfluxDB 2.x. This allow you to easily move from InfluxDB 1.x to InfluxDB 2.x Cloud or open source.

The following forward compatible APIs are available:

APIEndpointDescription
QueryApi.java/api/v2/queryQuery data in InfluxDB 1.8.0+ using the InfluxDB 2.x API and Flux (endpoint should be enabled by flux-enabled option)
WriteApi.java/api/v2/writeWrite data to InfluxDB 1.8.0+ using the InfluxDB 2.x API
health()/healthCheck the health of your InfluxDB instance

For detail info see InfluxDB 1.8 example.

Flux queries in InfluxDB 1.7+

Java - 图23

The following example demonstrates querying using the Flux language.

Installation

Java - 图24

Download the latest version:

Maven dependency:

Java - 图25

  1. <dependency>
  2. <groupId>com.influxdb</groupId>
  3. <artifactId>influxdb-client-flux</artifactId>
  4. <version>7.2.0</version>
  5. </dependency>
Or when using Gradle:

Java - 图26

  1. dependencies {
  2. implementation "com.influxdb:influxdb-client-flux:7.2.0"
  3. }
  1. package example;
  2. import java.util.List;
  3. import com.influxdb.client.flux.FluxClient;
  4. import com.influxdb.client.flux.FluxClientFactory;
  5. import com.influxdb.query.FluxRecord;
  6. import com.influxdb.query.FluxTable;
  7. public class FluxExample {
  8. public static void main(String[] args) {
  9. FluxClient fluxClient = FluxClientFactory.create("http://localhost:8086/");
  10. //
  11. // Flux
  12. //
  13. String flux = "from(bucket: \"telegraf\")\n" +
  14. " |> range(start: -1d)" +
  15. " |> filter(fn: (r) => (r[\"_measurement\"] == \"cpu\" and r[\"_field\"] == \"usage_system\"))" +
  16. " |> sample(n: 5, pos: 1)";
  17. //
  18. // Synchronous query
  19. //
  20. List<FluxTable> tables = fluxClient.query(flux);
  21. for (FluxTable fluxTable : tables) {
  22. List<FluxRecord> records = fluxTable.getRecords();
  23. for (FluxRecord fluxRecord : records) {
  24. System.out.println(fluxRecord.getTime() + ": " + fluxRecord.getValueByKey("_value"));
  25. }
  26. }
  27. //
  28. // Asynchronous query
  29. //
  30. fluxClient.query(flux, (cancellable, record) -> {
  31. // process the flux query result record
  32. System.out.println(record.getTime() + ": " + record.getValue());
  33. }, error -> {
  34. // error handling while processing result
  35. System.out.println("Error occurred: "+ error.getMessage());
  36. }, () -> {
  37. // on complete
  38. System.out.println("Query completed");
  39. });
  40. fluxClient.close();
  41. }
  42. }

Build Requirements

Java - 图27

  • Java 17+ (tested with JDK 17)
    • ⚠️ If you want to use older version of JDK, you have to use the 6.x version of the client.
  • Maven 3.0+ (tested with maven 3.5.0)
  • Docker daemon running
  • The latest InfluxDB 2.x and InfluxDB 1.X docker instances, which can be started using the ./scripts/influxdb-restart.sh script

Once these are in place you can build influxdb-client-java with all tests with:

  1. $ mvn clean install

If you don’t have Docker running locally, you can skip tests with the -DskipTests flag set to true:

  1. $ mvn clean install -DskipTests=true

If you have Docker running, but it is not available over localhost (e.g. you are on a Mac and using docker-machine) you can set optional environment variables to point to the correct IP addresses and ports:

  • INFLUXDB_IP
  • INFLUXDB_PORT_API
  • INFLUXDB_2_IP
  • INFLUXDB_2_PORT_API
  1. $ export INFLUXDB_IP=192.168.99.100
  2. $ mvn test

Contributing

Java - 图28

If you would like to contribute code you can do through GitHub by forking the repository and sending a pull request into the master branch.

License

Java - 图29

The InfluxDB 2.x JVM Based Clients are released under the MIT License.