Java SDK 指南¶
本文介绍如何使用 Java SDK 连接悦数图数据库开发版并进行简单查询。
前提条件¶
- 已安装 JDK 8。
- 对于本地部署用户,悦数图数据库开发版服务组正在运行中。更多信息,请参见快速开始。
操作步骤¶
-
将 Java SDK 导入到您的 Java 项目中。例如,使用 Maven 导入时,需将以下依赖项添加到
pom.xml文件:<dependency> <groupId>com.vesoft</groupId> <artifactId>driver</artifactId> <version>5.3.1</version> </dependency>注意:如果你引用了悦数图数据库开发版 SDK 依赖的项目在打包成 JAR 后,运行时出现
java.lang.IllegalArgumentException: Address types of NameResolver 'unix' for '192.168.15.8:9669' not supported by transport错误,请在你项目的 pom.xml 中 添加插件 maven-shade-plugin 并配置 transformer:<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> -
选择以下任一方法连接悦数图数据库开发版并执行查询:
Note
针对本地部署用户,在连接悦数图数据库开发版时,除了指定用户名和密码外,还可以启用无会话模式。该模式允许您不提供身份验证信息。更多信息,请参见无会话模式。
-
如果只有一个客户端需要与悦数图数据库开发版交互,您可以使用客户端(
client)建立连接并执行查询。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(); } }
-
如果有多个客户端需要同时与悦数图数据库开发版交互,您可以创建连接池(
pool)以管理一组连接。您可以使用池获取客户端(client)并在查询执行后将其返回。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(); } }
参数
<host>、<port>、<username>和<password>须替换为实际的悦数图数据库开发版连接信息。 -