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");
        }
    }

    @Override
    public 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);
        }
    }

    @Override
    public Class<?> getObjectType() {
        return Session.class;
    }

    public Session getSession() {
        return (Session) getObject();
    }

    @Override
    public void destroy() throws Exception {
        nebulaPool.close();
    }

}
  • SpringBoot自动配置
@EnableConfigurationProperties({ NebulaGraphProperties.class })
@Configuration
public class NebulaGraphAutoConfiguration {

    @ConditionalOnProperty(name = "nebula-graph.enable", havingValue = "true", matchIfMissing = false)
    @Bean
    public 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: false
  cluster-nodes:
    - 192.168.0.1:9559
    - 192.168.0.1:9669
  max-connect-size: 10
  username: root
  password: 123456
  • 项目引入部分代码
@Slf4j
@Service("nebulaGraphService")
public class NebulaGraphServiceImpl implements NebulaGraphService {

    private static final String SPACE_QL = "USE %s";

    @Autowired
    private 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;
    }

    @Override
    public <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);
    }

    @Override
    public <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;
    }

}
总体来说,跟普通的数据库连接还是很相似的,上手也是比较容易的。
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
《Python学习笔记》是由皮大庆编写的一本关于Python语言学习的教材。在这本书中,作者详细介绍了Python语言的基础知识、语法规则以及常用的编程技巧。 首先,作者简要介绍了Python语言的特点和优势。他提到,Python是一种易于学习和使用的编程语言,受到了广大程序员的喜爱。Python具有简洁、清晰的语法结构,使得代码可读性极高,同时也提供了丰富的库和模块,能够快速实现各种功能。 接着,作者详细讲解了Python的基本语法。他从变量、数据类型、运算符等基础知识开始,逐步介绍了条件语句、循环控制、函数、模块等高级概念。同时,作者通过大量的示例代码和实践案例,帮助读者加深对Python编程的理解和应用。 在书中,作者还特别强调了编写规范和良好的编程习惯。他从命名规范、注释风格、代码缩进等方面指导读者如何写出清晰、可读性强的Python代码。作者认为,良好的编程习惯对于提高代码质量和提高工作效率非常重要。 此外,作者还介绍了Python的常用库和模块。他提到了一些常用的库,如Numpy、Pandas、Matplotlib等。这些库在数据处理、科学计算、可视化等领域有广泛的应用,帮助读者更好地解决实际问题。 总的来说,《Python学习笔记》是一本非常实用和全面的Python学习教材。通过学习这本书,读者可以系统地学习和掌握Python编程的基础知识和高级应用技巧,为以后的编程学习和工作打下坚实的基础。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值