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

相关文章

java.sql.SQLTransientConnectionException连接超时异常原因及解决方案

《java.sql.SQLTransientConnectionException连接超时异常原因及解决方案》:本文主要介绍java.sql.SQLTransientConnectionExcep... 目录一、引言二、异常信息分析三、可能的原因3.1 连接池配置不合理3.2 数据库负载过高3.3 连接泄漏

Vite 打包目录结构自定义配置小结

《Vite打包目录结构自定义配置小结》在Vite工程开发中,默认打包后的dist目录资源常集中在asset目录下,不利于资源管理,本文基于Rollup配置原理,本文就来介绍一下通过Vite配置自定义... 目录一、实现原理二、具体配置步骤1. 基础配置文件2. 配置说明(1)js 资源分离(2)非 JS 资

Mac电脑如何通过 IntelliJ IDEA 远程连接 MySQL

《Mac电脑如何通过IntelliJIDEA远程连接MySQL》本文详解Mac通过IntelliJIDEA远程连接MySQL的步骤,本文通过图文并茂的形式给大家介绍的非常详细,感兴趣的朋友跟... 目录MAC电脑通过 IntelliJ IDEA 远程连接 mysql 的详细教程一、前缀条件确认二、打开 ID

Unity新手入门学习殿堂级知识详细讲解(图文)

《Unity新手入门学习殿堂级知识详细讲解(图文)》Unity是一款跨平台游戏引擎,支持2D/3D及VR/AR开发,核心功能模块包括图形、音频、物理等,通过可视化编辑器与脚本扩展实现开发,项目结构含A... 目录入门概述什么是 UnityUnity引擎基础认知编辑器核心操作Unity 编辑器项目模式分类工程

Go语言连接MySQL数据库执行基本的增删改查

《Go语言连接MySQL数据库执行基本的增删改查》在后端开发中,MySQL是最常用的关系型数据库之一,本文主要为大家详细介绍了如何使用Go连接MySQL数据库并执行基本的增删改查吧... 目录Go语言连接mysql数据库准备工作安装 MySQL 驱动代码实现运行结果注意事项Go语言执行基本的增删改查准备工作

聊聊springboot中如何自定义消息转换器

《聊聊springboot中如何自定义消息转换器》SpringBoot通过HttpMessageConverter处理HTTP数据转换,支持多种媒体类型,接下来通过本文给大家介绍springboot中... 目录核心接口springboot默认提供的转换器如何自定义消息转换器Spring Boot 中的消息

python连接sqlite3简单用法完整例子

《python连接sqlite3简单用法完整例子》SQLite3是一个内置的Python模块,可以通过Python的标准库轻松地使用,无需进行额外安装和配置,:本文主要介绍python连接sqli... 目录1. 连接到数据库2. 创建游标对象3. 创建表4. 插入数据5. 查询数据6. 更新数据7. 删除

Python学习笔记之getattr和hasattr用法示例详解

《Python学习笔记之getattr和hasattr用法示例详解》在Python中,hasattr()、getattr()和setattr()是一组内置函数,用于对对象的属性进行操作和查询,这篇文章... 目录1.getattr用法详解1.1 基本作用1.2 示例1.3 原理2.hasattr用法详解2.

Python自定义异常的全面指南(入门到实践)

《Python自定义异常的全面指南(入门到实践)》想象你正在开发一个银行系统,用户转账时余额不足,如果直接抛出ValueError,调用方很难区分是金额格式错误还是余额不足,这正是Python自定义异... 目录引言:为什么需要自定义异常一、异常基础:先搞懂python的异常体系1.1 异常是什么?1.2

在 Spring Boot 中连接 MySQL 数据库的详细步骤

《在SpringBoot中连接MySQL数据库的详细步骤》本文介绍了SpringBoot连接MySQL数据库的流程,添加依赖、配置连接信息、创建实体类与仓库接口,通过自动配置实现数据库操作,... 目录一、添加依赖二、配置数据库连接三、创建实体类四、创建仓库接口五、创建服务类六、创建控制器七、运行应用程序八