Java SDK guide¶
This guide introduces how to set up the Java SDK to connect to NebulaGraph and perform simple queries.
Prerequisites¶
- JDK 8 is installed.
- Connection information is obtained from NebulaGraph Cloud. For more information, see Connect to your database.
Steps¶
-
Import the Java SDK into your Java project. For example, to import with Maven, add the following dependency to the
pom.xml
file:<dependency> <groupId>com.vesoft</groupId> <artifactId>driver</artifactId> <version>5.0.0</version> </dependency>
Note: After you reference the NebulaGraph SDK dependency in a project and package it as a JAR file, if you encounter the exception
java.lang.IllegalArgumentException: Address types of NameResolver 'unix' for '192.168.15.8:9669' not supported by transport
when running this JAR file, add the pluginmaven-shade-plugin
to your project'spom.xml
file and configure the transformer as follows:<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.4.1</version> <configuration> <!-- put your configurations here --> <filters> <filter> <artifact>*:*</artifact> </filter> </filters> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"> </transformer> </transformers> </configuration> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> </execution> </executions> </plugin>
-
Select either of the following methods to connect to NebulaGraph and execute queries:
-
If only one client needs to interact with NebulaGraph, you can use the client to establish a direct connection and execute queries.
NebulaClient client = null; try { client = NebulaClient.builder("<host>:<port>", "<username>", "<password>") .withAuthOptions(Collections.emptyMap()) .withConnectTimeoutMills(1000) .withRequestTimeoutMills(3000) .build(); client.execute("USE nba MATCH (v:player) RETURN v.id, v.name, v.score, v.gender, v.rate"); } catch (Exception e) { throw e; } finally { if (client != null) { client.close(); } }
-
If multiple clients need to interact with NebulaGraph simultaneously, you can create a connection pool to manage a set of connections. You can use the pool to get a client and return it after queries are executed.
NebulaPool pool = null; try { pool = NebulaPool .builder("<host>:<port>", "<username>", "<password>") .withMaxClientSize(10) .withMinClientSize(1) .withConnectTimeoutMills(1000) .withRequestTimeoutMills(30000) .withBlockWhenExhausted(true) .withMaxWaitMills(Long.MAX_VALUE) .build(); NebulaClient client = pool.getClient(); client.execute("USE nba MATCH (v:player) RETURN v.id, v.name, v.score, v.gender, v.rate"); pool.returnClient(client); } catch (Exception e) { throw e; } finally { if (pool != null) { pool.close(); } }
Replace
<host>
,<port>
,<username>
, and<password>
with the actual connection information obtained from NebulaGraph Cloud. -