Connecting to ClickHouse with Java
In this example we will be using the official Java client maintained by the ClickHouse team. Before you begin, it is imperative to review the general steps and considerations for connecting to a ClickHouse cluster as outlined in Connecting to a ClickHouse Cluster.
1. Add the dependencies below to your project
For tarball installation:
1 2 3 4 5 6 7 8 9 10 11 12 |
<dependencies> <dependency> <groupId>com.clickhouse</groupId> <artifactId>clickhouse-http-client</artifactId> <version>0.6.0</version> <dependency> <dependency> <groupId>org.apache.httpcomponents.client5</groupId> <artifactId>httpclient5</artifactId> <version>5.2.3</version> <dependency> <dependencies> |
2. Use this code below to build connections to the nodes and try executing a SELECT query on the cluster
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import com.clickhouse.client.*; import com.clickhouse.client.config.ClickHouseClientOption; import com.clickhouse.client.config.ClickHouseSslMode; import com.clickhouse.data.ClickHouseFormat; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class ClickhouseClient { public static void main(String[] args) throws ClickHouseException { ClickHouseCluster cluster = ClickHouseCluster.of("f95e6eeb-9a7b-4866-a357-e643c1a31db4", buildNodes(List.of("ip-54-235-186-192.9736e71d4a9c41299e993646add8e071.cu.dev.instaclustr.com","ip-52-200-239-133.9736e71d4a9c41299e993646add8e071.cu.dev.instaclustr.com","ip-3-215-239-34.9736e71d4a9c41299e993646add8e071.cu.dev.instaclustr.com")) ); try (ClickHouseClient client = ClickHouseClient.newInstance(ClickHouseProtocol.HTTP); ClickHouseResponse response = client.read(cluster) .format(ClickHouseFormat.RowBinaryWithNamesAndTypes) .query("SHOW CLUSTERS") .executeAndWait(); ) { System.out.println(response.firstRecord().getValue("cluster").asString()); } } private static List<ClickHouseNode> buildNodes(final List<String> hostnames) { return hostnames.stream().map(ClickhouseClient::buildNode).collect(Collectors.toList()); } private static ClickHouseNode buildNode(final String hostname) { return ClickHouseNode.builder() .host(hostname) .port(ClickHouseProtocol.HTTP, 8443) .credentials(ClickHouseCredentials.fromUserAndPassword( "icclickhouse", "password-for-icclickhouse")) .options( Map.of( ClickHouseClientOption.SSL.getKey(), "true", ClickHouseClientOption.SSL_ROOT_CERTIFICATE.getKey(), "path/to/isrgrootx1.pem", ClickHouseClientOption.COMPRESS.getKey(), "0" )).build(); } } |
Simply replace the password of the icclickhouse user with that from the Connection Info page. The isrgrootx1.pem file is also available for downloading from the same page on the console.