Updated on 2024-10-08 GMT+08:00

Connecting to an Instance Using Java

This section describes how to connect to a GeminiDB Influx instance using the Java programming language.

Dependencies on the pom File

<dependency>
  <groupId>org.influxdb</groupId>
  <artifactId>influxdb-java</artifactId>
  <version>2.21</version>
</dependency>

Example Code for Connecting to an Instance Using SSL

package influxdb;

 import java.security.SecureRandom;
 import java.security.cert.X509Certificate;
 import java.util.concurrent.TimeUnit;
 import javax.net.ssl.SSLContext;

 import okhttp3.OkHttpClient;
 import org.influxdb.InfluxDB;
 import org.influxdb.InfluxDBFactory;
 import org.influxdb.dto.Point;
 import org.influxdb.dto.Query;
 import org.influxdb.dto.QueryResult;

 import org.apache.http.ssl.SSLContexts;
 import javax.net.ssl.*;

 public class demo {
     public static void main(String[] args) {
         OkHttpClient.Builder client = new OkHttpClient.Builder()
             .connectTimeout(10, TimeUnit.SECONDS)
             .writeTimeout(10, TimeUnit.SECONDS)
             .readTimeout(10, TimeUnit.SECONDS)
             .retryOnConnectionFailure(true);

         client.sslSocketFactory(defaultSslSocketFactory(), defaultTrustManager());
         client.hostnameVerifier(noopHostnameVerifier());

        // There will be security risks if the username and password used for authentication are directly written into code. Store the username and password in ciphertext in the configuration file or environment variables.
        // In this example, the username and password are stored in the environment variables. Before running this example, set environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV as needed.
         String username = System.getenv("EXAMPLE_USERNAME_ENV");
         String password = System.getenv("EXAMPLE_PASSWORD_ENV");
         final String serverURL = "https://127.0.0.1:8086", username = username, password = password;

         InfluxDB influxdb = InfluxDBFactory.connect(serverURL, username, password, client);

         // Create a database...
         String databaseName = "foo";
         influxdb.query(new Query("CREATE DATABASE " + databaseName, databaseName));
         influxdb.setDatabase(databaseName);

         // Write points to influxdb.
         influxdb.write(Point.measurement("bar")
             .time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
             .tag("location", "chengdu")
             .addField("temperature", 22)
             .build());

         // Query your data using InfluxQL.
         QueryResult queryResult = influxdb.query(new Query("SELECT * FROM bar", databaseName));

         // Close it if your application is terminating or you are not using it anymore.
         influxdb.close();
     }

     private static X509TrustManager defaultTrustManager() {
         return new X509TrustManager() {
             public X509Certificate[] getAcceptedIssuers() {
                 return new X509Certificate[0];
             }

             public void checkClientTrusted(X509Certificate[] certs, String authType) {
             }

             public void checkServerTrusted(X509Certificate[] certs, String authType) {
             }
         };
     }

     private static SSLSocketFactory defaultSslSocketFactory() {
         try {
             SSLContext sslContext = SSLContexts.createDefault();

             sslContext.init(null, new TrustManager[] {
                 defaultTrustManager()
             }, new SecureRandom());
             return sslContext.getSocketFactory();
         } catch (Exception e) {
             throw new RuntimeException(e);
         }

     }

     private static HostnameVerifier noopHostnameVerifier() {
         return new HostnameVerifier() {
             @Override
             public boolean verify(final String s, final SSLSession sslSession) { 
                 return true; //true indicates that SSL is enabled but the SSL certificate is not verified. This mode is recommended.
             }
         };
     }
 }

Example Java Code for Connecting to an Instance Using an Unencrypted Connection

package influxdb;

import okhttp3.OkHttpClient;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;

import java.util.concurrent.TimeUnit;

public class demoNoSSL {
    public static void main(String[] args) {
        OkHttpClient.Builder client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true);

        // There will be security risks if the username and password used for authentication are directly written into code. Store the username and password in ciphertext in the configuration file or environment variables.
        // In this example, the username and password are stored in the environment variables. Before running this example, set environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV as needed.
        String username = System.getenv("EXAMPLE_USERNAME_ENV");
        String password = System.getenv("EXAMPLE_PASSWORD_ENV");
        final String serverURL = "http://127.0.0.1:8086", username = username, password = password;
        InfluxDB influxdb = InfluxDBFactory.connect(serverURL, username, password, client);

        // Create a database...
        String databaseName = "foo";

        influxdb.query(new Query("CREATE DATABASE " + databaseName, databaseName));
        influxdb.setDatabase(databaseName);

        // Write points to influxdb.
        influxdb.write(Point.measurement("bar")
                .time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
                .tag("location", "chengdu")
                .addField("temperature", 22)
                .build());

        // Query your data using InfluxQL.
        QueryResult queryResult = influxdb.query(new Query("SELECT * FROM bar", databaseName));

        // Close it if your application is terminating or you are not using it anymore.
        influxdb.close();
    }
}

Example Java Code for Connecting to an Instance Using the Connection Pool

package influxdb;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;

import java.util.concurrent.TimeUnit;

public class demoConnectionPool {
    public static void main(String[] args) {
        // The client connection pool is based on OkHttpClient.
        OkHttpClient.Builder client = new OkHttpClient().newBuilder();
        client.connectTimeout(10, TimeUnit.SECONDS);
        client.readTimeout(10, TimeUnit.SECONDS);
        client.writeTimeout(10, TimeUnit.SECONDS);
        // Set this parameter to true to mask some connection errors so that the system automatically retries.
        client.retryOnConnectionFailure(true);
        // Maximum number of idle connections in the connection pool. The default value is 5.
        // The connection that stays idle longer than the threshold will be disabled by the connection pool. Then sockets enter into the TIME_WAIT status for the system to reclaim. Set parameter new ConnectionPool based on the number of the idle connections.
        client.connectionPool(new ConnectionPool(5, 30, TimeUnit.SECONDS));

        // There will be security risks if the username and password used for authentication are directly written into code. Store the username and password in ciphertext in the configuration file or environment variables.
        // In this example, the username and password are stored in the environment variables. Before running this example, set environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV as needed.
        String username = System.getenv("EXAMPLE_USERNAME_ENV");
        String password = System.getenv("EXAMPLE_PASSWORD_ENV");
        final String serverURL = "http://127.0.0.1:8086", username = username, password = password;
        InfluxDB influxdb = InfluxDBFactory.connect(serverURL, username, password, client);

        // Create a database...
        String databaseName = "foo";

        influxdb.query(new Query("CREATE DATABASE " + databaseName, databaseName));
        influxdb.setDatabase(databaseName);

        // Write points to influxdb.
        influxdb.write(Point.measurement("bar")
                .time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
                .tag("location", "chengdu")
                .addField("temperature", 22)
                .build());

        // Query your data using InfluxQL.
        QueryResult queryResult = influxdb.query(new Query("SELECT * FROM bar", databaseName));

        // Close it if your application is terminating or you are not using it anymore.
        influxdb.close();
    }
}

Example Java Code for Connecting to an Instance Using a Short Connection

/**
         Scenarios:
         * * When the ELB connection is used, the client sends multiple query requests at a time.
         * If HTTP persistent connections are used, most query requests are sent to one InfluxDB node, causing load imbalance.
         HTTP short connections (The value of Connection is close in the request header) can be used to achieve load balancing among InfluxDB nodes.
         */
/**
         In this mode, only part of the code is displayed.
         */
OkHttpClient.Builder client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .addNetworkInterceptor(chain -> {
                    Request newRequest = chain.request().newBuilder().header("Connection", "close").build();
                    return chain.proceed(newRequest);
                });