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中的交叉连接、自然连接和内连接查询,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、引入二、交php叉连接(cross join)三、自然连接(naturalandroid join)四

利用Python快速搭建Markdown笔记发布系统

《利用Python快速搭建Markdown笔记发布系统》这篇文章主要为大家详细介绍了使用Python生态的成熟工具,在30分钟内搭建一个支持Markdown渲染、分类标签、全文搜索的私有化知识发布系统... 目录引言:为什么要自建知识博客一、技术选型:极简主义开发栈二、系统架构设计三、核心代码实现(分步解析

python连接本地SQL server详细图文教程

《python连接本地SQLserver详细图文教程》在数据分析领域,经常需要从数据库中获取数据进行分析和处理,下面:本文主要介绍python连接本地SQLserver的相关资料,文中通过代码... 目录一.设置本地账号1.新建用户2.开启双重验证3,开启TCP/IP本地服务二js.python连接实例1.

Ubuntu中远程连接Mysql数据库的详细图文教程

《Ubuntu中远程连接Mysql数据库的详细图文教程》Ubuntu是一个以桌面应用为主的Linux发行版操作系统,这篇文章主要为大家详细介绍了Ubuntu中远程连接Mysql数据库的详细图文教程,有... 目录1、版本2、检查有没有mysql2.1 查询是否安装了Mysql包2.2 查看Mysql版本2.

Python3.6连接MySQL的详细步骤

《Python3.6连接MySQL的详细步骤》在现代Web开发和数据处理中,Python与数据库的交互是必不可少的一部分,MySQL作为最流行的开源关系型数据库管理系统之一,与Python的结合可以实... 目录环境准备安装python 3.6安装mysql安装pymysql库连接到MySQL建立连接执行S

使用Sentinel自定义返回和实现区分来源方式

《使用Sentinel自定义返回和实现区分来源方式》:本文主要介绍使用Sentinel自定义返回和实现区分来源方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Sentinel自定义返回和实现区分来源1. 自定义错误返回2. 实现区分来源总结Sentinel自定

如何自定义Nginx JSON日志格式配置

《如何自定义NginxJSON日志格式配置》Nginx作为最流行的Web服务器之一,其灵活的日志配置能力允许我们根据需求定制日志格式,本文将详细介绍如何配置Nginx以JSON格式记录访问日志,这种... 目录前言为什么选择jsON格式日志?配置步骤详解1. 安装Nginx服务2. 自定义JSON日志格式各

Spring Boot 整合 MyBatis 连接数据库及常见问题

《SpringBoot整合MyBatis连接数据库及常见问题》MyBatis是一个优秀的持久层框架,支持定制化SQL、存储过程以及高级映射,下面详细介绍如何在SpringBoot项目中整合My... 目录一、基本配置1. 添加依赖2. 配置数据库连接二、项目结构三、核心组件实现(示例)1. 实体类2. Ma

电脑win32spl.dll文件丢失咋办? win32spl.dll丢失无法连接打印机修复技巧

《电脑win32spl.dll文件丢失咋办?win32spl.dll丢失无法连接打印机修复技巧》电脑突然提示win32spl.dll文件丢失,打印机死活连不上,今天就来给大家详细讲解一下这个问题的解... 不知道大家在使用电脑的时候是否遇到过关于win32spl.dll文件丢失的问题,win32spl.dl

Android自定义Scrollbar的两种实现方式

《Android自定义Scrollbar的两种实现方式》本文介绍两种实现自定义滚动条的方法,分别通过ItemDecoration方案和独立View方案实现滚动条定制化,文章通过代码示例讲解的非常详细,... 目录方案一:ItemDecoration实现(推荐用于RecyclerView)实现原理完整代码实现