Nebula Graph - SpringBoot *** 作 Nebula

Nebula Graph - SpringBoot  *** 作 Nebula,第1张

一、Nebula Graph

前面两篇文章,讲解了下 Nebula Graph 的安装,及 nGQL 的使用,本篇文章讲解下在 java 环境下如何对 Nebula Graph 进行 *** 作,使用 SpringBoot 环境。

下面是上篇文章的地址:

https://blog.csdn.net/qq_43692950/article/details/124579284

二、SpringBoot *** 作 Nebula Graph
  • 首先引入 pom 依赖:

    
        com.vesoft
        client
        3.0.0
    
    

    为方便解析 json ,这里把 fastjson 也引进来。

    
        com.alibaba
        fastjson
        1.2.78
    
    
  • 配置文件中配置 Nebula 的信息,后面读取这里的配置信息。

    nebula:
      address[0]:
        host: 192.168.40.130
        port: 9669
      username: root
      password: root
      reconnect: false
      space: javatest
    
  • 声明 NebulaProperties 接收上面的配置信息:

    @Data
    public class NebulaAddress {
        private String host;
        private Integer port;
    }
    
    @Data
    @Configuration
    @ConfigurationProperties(prefix = "nebula")
    public class NebulaProperties {
        private List address;
        private String username;
        private String password;
        private boolean reconnect;
        private String space;
    }
    
  • 声明 NebulaConstant 把常用的字符串声明在这里:

    public class NebulaConstant {
        public static final String USE = "USE ";
        public static final String SEMICOLON = "; ";
        public static final String ERROR_CODE = "-1";
    
        @Getter
        @AllArgsConstructor
        public enum NebulaJson{
            ERRORS("errors"),
            CODE("code"),
            MESSAGE("message"),
            RESULTS("results"),
            COLUMNS("columns"),
            DATA("data"),
            ROW("row");
            private String key;
        }
    }
    
  • 声明 NebulaConfig ,初始化 NebulaPool ,及声明 Session 的获取方式:

    @Slf4j
    @Configuration
    public class NebulaConfig {
    
        @Bean
        public NebulaPool nebulaPool(NebulaProperties properties) throws UnknownHostException {
            NebulaPool pool = new NebulaPool();
            NebulaPoolConfig nebulaPoolConfig = new NebulaPoolConfig();
            nebulaPoolConfig.setMaxConnSize(1000);
            boolean init = pool.init(properties.getAddress().stream().map(d -> new HostAddress(d.getHost(), d.getPort())).collect(Collectors.toList()), nebulaPoolConfig);
            if (!init){
                throw new RuntimeException("NebulaGraph init err !");
            }else {
                log.info("NebulaGraph init Success !");
            }
            return pool;
        }
    
        @Bean
        @Scope(scopeName = "prototype",proxyMode = ScopedProxyMode.TARGET_CLASS)
        public Session session(NebulaPool nebulaPool,NebulaProperties properties) {
            try {
                Session session = nebulaPool.getSession(properties.getUsername(), properties.getPassword(), properties.isReconnect());
                session.execute(StringFormatter.concat(NebulaConstant.USE, properties.getSpace(), NebulaConstant.SEMICOLON).getValue());
                return session;
            } catch (Exception e) {
                log.error("get nebula session err , {} ", e.toString());
            }
            return null;
        }
    }
    
  • 为了方便对结果的解析,再声明一个 NebulaResult 用来接收结果:

    @Data
    public class NebulaResult {
        private Integer code;
        private String message;
        private List data;
    
        public boolean isSuccessed(){
            return code == 0;
        }
    }
    
  • 每次都是使用 Session 未免太麻烦,这里封装一个 NebulaTemplate 返回上面 对象 :

    @Slf4j
    @Component
    public class NebulaTemplate {
    
        @Resource
        Session session;
    
        public  NebulaResult queryObject(String stmt, Class tClass) {
            NebulaResult nebulaResult = executeObject(stmt);
            if (Objects.isNull(nebulaResult.getData())) {
                return nebulaResult;
            }
            Optional.ofNullable(nebulaResult.getData()).ifPresent(data -> nebulaResult.setData(data.stream().map(d -> JSONObject.toJavaObject(((JSONObject) d), tClass)).collect(Collectors.toList())));
            return nebulaResult;
        }
    
        public NebulaResult executeObject(String stmt) {
            JSONObject jsonObject = executeJson(stmt);
            return JSONObject.toJavaObject(jsonObject, NebulaResult.class);
        }
    
        public JSONObject executeJson(String stmt) {
            JSONObject restJson = new JSONObject();
            try {
                JSONObject jsonObject = JSON.parseObject(Objects.requireNonNull(session).executeJson(stmt));
                JSONObject errors = jsonObject.getJSONArray(NebulaConstant.NebulaJson.ERRORS.getKey()).getJSONObject(0);
                restJson.put(NebulaConstant.NebulaJson.CODE.getKey(), errors.getInteger(NebulaConstant.NebulaJson.CODE.getKey()));
                if (errors.getInteger(NebulaConstant.NebulaJson.CODE.getKey()) != 0) {
                    restJson.put(NebulaConstant.NebulaJson.MESSAGE.getKey(), errors.getString(NebulaConstant.NebulaJson.MESSAGE.getKey()));
                    return restJson;
                }
                JSONObject results = jsonObject.getJSONArray(NebulaConstant.NebulaJson.RESULTS.getKey()).getJSONObject(0);
                JSONArray columns = results.getJSONArray(NebulaConstant.NebulaJson.COLUMNS.getKey());
                if (Objects.isNull(columns)) {
                    return restJson;
                }
                JSONArray data = results.getJSONArray(NebulaConstant.NebulaJson.DATA.getKey());
                if (Objects.isNull(data)) {
                    return restJson;
                }
                List resultList = new ArrayList<>();
                data.stream().map(d -> (JSONObject) d).forEach(d -> {
                    JSONArray row = d.getJSONArray(NebulaConstant.NebulaJson.ROW.getKey());
                    JSONObject map = new JSONObject();
                    for (int i = 0; i < columns.size(); i++) {
                        map.put(columns.getString(i), row.get(i));
                    }
                    resultList.add(map);
                });
                restJson.put(NebulaConstant.NebulaJson.DATA.getKey(), resultList);
            } catch (Exception e) {
                restJson.put(NebulaConstant.NebulaJson.CODE.getKey(), NebulaConstant.ERROR_CODE);
                restJson.put(NebulaConstant.NebulaJson.MESSAGE.getKey(), e.toString());
                log.error("nebula execute err:", e);
            }
            return restJson;
        }
    }
    
  • 测试

    @RestController
    public class TestController {
    
        @Resource
        NebulaTemplate nebulaTemplate;
    
        @GetMapping("/addVertex")
        public Object addJSON() throws IOErrorException {
            String sql = "insert vertex team(team_name, persion_num) values \"team_2\":(\"team_2\", 43);";
            NebulaResult nebulaResult = nebulaTemplate.executeObject(sql);
            return nebulaResult;
        }
    
        @GetMapping("/findVertex")
        public Object findJson2() throws IOErrorException {
            String sql = "lookup on team  yield id(vertex) AS id,properties(vertex).persion_num AS persion_num,properties(vertex).team_name AS team_name;";
            NebulaResult infoNebulaResult = nebulaTemplate.queryObject(sql, Info.class);
            return infoNebulaResult;
        }
    }
    


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/871301.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-13
下一篇2022-05-13

发表评论

登录后才能评论

评论列表(0条)

    保存