NebulaGraph学习笔记-自定义池连接

2024-02-21 21:04

本文主要是介绍NebulaGraph学习笔记-自定义池连接,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

最近项目需要连接NebulaGraph图数据库获取部分数据,于是查看了一些相关资料,发现可以通过类似数据库连接池NebulaPool方式连接。主要也是以下几个部分:创建连接池,、创建会话、执行查询、解析结果。下面是一个简单的DEMO记录。
组件项目
  • 相关依赖包
<!-- SpringBoot依赖包 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot</artifactId>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId>
</dependency><!-- Client依赖包 -->
<dependency><groupId>com.vesoft</groupId><artifactId>client</artifactId><version>3.6.1</version>
</dependency>
  • NebulaGraph连接属性类
@Data
@ConfigurationProperties(prefix = "nebula-graph")
public class NebulaGraphProperties {/** 是否开启 **/private Boolean enable = false;/** 集群节点 */private String[] clusterNodes = null;/** Max Connect Size */private int maxConnectSize = 10;/** 用户名 */private String username;/** 密码 */private String password;}
  • NebulaGraph连接池类
public class NebulaGraphFactoryBean implements FactoryBean, DisposableBean {private NebulaGraphProperties nebulaGraphProperties;private NebulaPool nebulaPool;public NebulaGraphFactoryBean(NebulaGraphProperties nebulaGraphProperties) {this.nebulaGraphProperties = nebulaGraphProperties;String[] clusterNodes = nebulaGraphProperties.getClusterNodes();if (null == clusterNodes || clusterNodes.length == 0) {return;}List<HostAddress> hostAddresses = new ArrayList<>();for (int i = 0, len = clusterNodes.length; i < len; i++) {String clusterNode = clusterNodes[i];if (!clusterNode.contains(":")) {continue;}String[] ipAndPort = clusterNode.split(":");if (ipAndPort.length != 2 || !ipAndPort[1].matches("\\d+")) {throw new RuntimeException("Invalid Nebula Graph Node " + clusterNode);}hostAddresses.add(new HostAddress(ipAndPort[0], Integer.parseInt(ipAndPort[1])));}NebulaPoolConfig nebulaPoolConfig = new NebulaPoolConfig();nebulaPoolConfig.setMaxConnSize(nebulaGraphProperties.getMaxConnectSize());nebulaPool = new NebulaPool();try {nebulaPool.init(hostAddresses, nebulaPoolConfig);} catch (UnknownHostException e) {throw new RuntimeException("Unknown Nebula Graph Host");}}@Overridepublic Object getObject() {try {return nebulaPool.getSession(nebulaGraphProperties.getUsername(), nebulaGraphProperties.getPassword(), false);} catch (NotValidConnectionException | IOErrorException | AuthFailedException | ClientServerIncompatibleException e) {throw new RuntimeException("Nebula graph session exception", e);}}@Overridepublic Class<?> getObjectType() {return Session.class;}public Session getSession() {return (Session) getObject();}@Overridepublic void destroy() throws Exception {nebulaPool.close();}}
  • SpringBoot自动配置
@EnableConfigurationProperties({ NebulaGraphProperties.class })
@Configuration
public class NebulaGraphAutoConfiguration {@ConditionalOnProperty(name = "nebula-graph.enable", havingValue = "true", matchIfMissing = false)@Beanpublic NebulaGraphFactoryBean nebulaGraphFactoryBean(NebulaGraphProperties nebulaGraphProperties) {return new NebulaGraphFactoryBean(nebulaGraphProperties);}}
  • spring.factories文件开启自动配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\com.component.nebula.graph.config.NebulaGraphAutoConfiguration
业务项目
  • 引入组件项目
<!--ComponentNebulaGraph依赖包-->
<dependency><groupId>com.component</groupId><artifactId>component-nebula-graph</artifactId><version>1.0.0-SNAPSHOT</version>
</dependency>
  • 项目引入配置
nebula-graph:enable: falsecluster-nodes:- 192.168.0.1:9559- 192.168.0.1:9669max-connect-size: 10username: rootpassword: 123456
  • 项目引入部分代码
@Slf4j
@Service("nebulaGraphService")
public class NebulaGraphServiceImpl implements NebulaGraphService {private static final String SPACE_QL = "USE %s";@Autowiredprivate NebulaGraphFactoryBean nebulaGraphFactoryBean;public NGResultV1DTO execute(String space, String ngql, Map<String, Object> parameterMap) throws IOErrorException {Session session = nebulaGraphFactoryBean.getSession();NGResultV1DTO ngResultV1DTO = JsonUtils.json(session.executeJson(String.format(SPACE_QL, space)), NGResultV1DTO.class);if (!ngResultV1DTO.isSuccess()) {return ngResultV1DTO;}String result = null == parameterMap ? session.executeJson(ngql) : session.executeJsonWithParameter(ngql, parameterMap);log.info("execute result {}", result);ngResultV1DTO = JsonUtils.json(result, NGResultV1DTO.class);return ngResultV1DTO;}@Overridepublic <T> ResultDTO<T> executeOne(String space, String ngql, Map<String, Object> parameterMap, Class<T> clazz) throws IOErrorException {return buildResultDTO(execute(space, ngql, parameterMap), clazz, true);}@Overridepublic <T> ResultDTO<List<T>> execute(String space, String ngql, Map<String, Object> parameterMap, Class<T> clazz) throws IOErrorException {return buildResultDTO(execute(space, ngql, parameterMap), clazz, false);}private <T> ResultDTO buildResultDTO(NGResultV1DTO ngResultV1DTO, Class<T> clazz, boolean isSingleResult) throws IOErrorException {if (!ngResultV1DTO.isSuccess()) {NGResultV1DTO.Error error = ngResultV1DTO.getErrors().get(0);return ResultDTO.fail(error.getCode(), error.getMessage());}List<T> resultList = parse(ngResultV1DTO, clazz);return ResultDTO.success(!ObjectUtil.isEmpty(resultList) && isSingleResult ? resultList.get(0) : resultList);}private <T> List<T> parse(NGResultV1DTO ngResultV1DTO, Class<T> clazz) {List<NGResultV1DTO.Result> results = ngResultV1DTO.getResults();if (null == results || results.isEmpty()) {return null;}NGResultV1DTO.Result result = results.get(0);List<NGResultV1DTO.Data> datas = result.getDatas();if (null == datas || datas.isEmpty()) {return null;}boolean needColumns = false;List<String> columns = result.getColumns();List<T> targetList = new ArrayList<>();for (int i = 0, len = datas.size(); i < len; i++) {NGResultV1DTO.Data data = datas.get(i);List<?> rows = data.getRows();if (null == rows || rows.isEmpty()) {continue;}if (i == 0) {List<?> metas = data.getMetas();if (null == metas || null == metas.get(0)) {needColumns = true;}}Object row = rows.get(0);Map<String, Object> dataMap = new HashMap<>();if (needColumns) {Object[] rowArray = (Object[]) row;for (int j = 0, jLen = rowArray.length; j < jLen; j++) {dataMap.put(columns.get(j), rowArray[j]);}} else {((Map<String, Object>) row).forEach((key, value) -> {if (key.contains(".")) {String[] keyArray = key.split(".");dataMap.put(keyArray[keyArray.length - 1], value);} else {dataMap.put(key, value);}});}targetList.add(ReflectUtils.convertMapToObject(dataMap, clazz));}return targetList;}}
总体来说,跟普通的数据库连接还是很相似的,上手也是比较容易的。

这篇关于NebulaGraph学习笔记-自定义池连接的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/733060

相关文章

MySQL中的表连接原理分析

《MySQL中的表连接原理分析》:本文主要介绍MySQL中的表连接原理分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、背景2、环境3、表连接原理【1】驱动表和被驱动表【2】内连接【3】外连接【4编程】嵌套循环连接【5】join buffer4、总结1、背景

Java实现自定义table宽高的示例代码

《Java实现自定义table宽高的示例代码》在桌面应用、管理系统乃至报表工具中,表格(JTable)作为最常用的数据展示组件,不仅承载对数据的增删改查,还需要配合布局与视觉需求,而JavaSwing... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码

一文详解Java Stream的sorted自定义排序

《一文详解JavaStream的sorted自定义排序》Javastream中的sorted方法是用于对流中的元素进行排序的方法,它可以接受一个comparator参数,用于指定排序规则,sorte... 目录一、sorted 操作的基础原理二、自定义排序的实现方式1. Comparator 接口的 Lam

SpringBoot连接Redis集群教程

《SpringBoot连接Redis集群教程》:本文主要介绍SpringBoot连接Redis集群教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1. 依赖2. 修改配置文件3. 创建RedisClusterConfig4. 测试总结1. 依赖 <de

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

如何自定义一个log适配器starter

《如何自定义一个log适配器starter》:本文主要介绍如何自定义一个log适配器starter的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录需求Starter 项目目录结构pom.XML 配置LogInitializer实现MDCInterceptor

java连接opcua的常见问题及解决方法

《java连接opcua的常见问题及解决方法》本文将使用EclipseMilo作为示例库,演示如何在Java中使用匿名、用户名密码以及证书加密三种方式连接到OPCUA服务器,若需要使用其他SDK,原理... 目录一、前言二、准备工作三、匿名方式连接3.1 匿名方式简介3.2 示例代码四、用户名密码方式连接4

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

MySQL 表的内外连接案例详解

《MySQL表的内外连接案例详解》本文给大家介绍MySQL表的内外连接,结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录表的内外连接(重点)内连接外连接表的内外连接(重点)内连接内连接实际上就是利用where子句对两种表形成的笛卡儿积进行筛选,我

Apache 高级配置实战之从连接保持到日志分析的完整指南

《Apache高级配置实战之从连接保持到日志分析的完整指南》本文带你从连接保持优化开始,一路走到访问控制和日志管理,最后用AWStats来分析网站数据,对Apache配置日志分析相关知识感兴趣的朋友... 目录Apache 高级配置实战:从连接保持到日志分析的完整指南前言 一、Apache 连接保持 - 性