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

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

W外链微信推广短连接怎么做?

制作微信推广链接的难点分析 一、内容创作难度 制作微信推广链接时,首先需要创作有吸引力的内容。这不仅要求内容本身有趣、有价值,还要能够激起人们的分享欲望。对于许多企业和个人来说,尤其是那些缺乏创意和写作能力的人来说,这是制作微信推广链接的一大难点。 二、精准定位难度 微信用户群体庞大,不同用户的需求和兴趣各异。因此,制作推广链接时需要精准定位目标受众,以便更有效地吸引他们点击并分享链接

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

学习hash总结

2014/1/29/   最近刚开始学hash,名字很陌生,但是hash的思想却很熟悉,以前早就做过此类的题,但是不知道这就是hash思想而已,说白了hash就是一个映射,往往灵活利用数组的下标来实现算法,hash的作用:1、判重;2、统计次数;

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

【机器学习】高斯过程的基本概念和应用领域以及在python中的实例

引言 高斯过程(Gaussian Process,简称GP)是一种概率模型,用于描述一组随机变量的联合概率分布,其中任何一个有限维度的子集都具有高斯分布 文章目录 引言一、高斯过程1.1 基本定义1.1.1 随机过程1.1.2 高斯分布 1.2 高斯过程的特性1.2.1 联合高斯性1.2.2 均值函数1.2.3 协方差函数(或核函数) 1.3 核函数1.4 高斯过程回归(Gauss

【学习笔记】 陈强-机器学习-Python-Ch15 人工神经网络(1)sklearn

系列文章目录 监督学习:参数方法 【学习笔记】 陈强-机器学习-Python-Ch4 线性回归 【学习笔记】 陈强-机器学习-Python-Ch5 逻辑回归 【课后题练习】 陈强-机器学习-Python-Ch5 逻辑回归(SAheart.csv) 【学习笔记】 陈强-机器学习-Python-Ch6 多项逻辑回归 【学习笔记 及 课后题练习】 陈强-机器学习-Python-Ch7 判别分析 【学

系统架构师考试学习笔记第三篇——架构设计高级知识(20)通信系统架构设计理论与实践

本章知识考点:         第20课时主要学习通信系统架构设计的理论和工作中的实践。根据新版考试大纲,本课时知识点会涉及案例分析题(25分),而在历年考试中,案例题对该部分内容的考查并不多,虽在综合知识选择题目中经常考查,但分值也不高。本课时内容侧重于对知识点的记忆和理解,按照以往的出题规律,通信系统架构设计基础知识点多来源于教材内的基础网络设备、网络架构和教材外最新时事热点技术。本课时知识

线性代数|机器学习-P36在图中找聚类

文章目录 1. 常见图结构2. 谱聚类 感觉后面几节课的内容跨越太大,需要补充太多的知识点,教授讲得内容跨越较大,一般一节课的内容是书本上的一章节内容,所以看视频比较吃力,需要先预习课本内容后才能够很好的理解教授讲解的知识点。 1. 常见图结构 假设我们有如下图结构: Adjacency Matrix:行和列表示的是节点的位置,A[i,j]表示的第 i 个节点和第 j 个