Nebula Graph - SpringBoot 操作 Nebula

2022-06-16 00:00:00 专区 订阅 配置 文章 声明

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

下面是上篇文章的地址:

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

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

<dependency>
<groupId>com.vesoft</groupId>
<artifactId>client</artifactId>
<version>3.0.0</version>
</dependency>

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

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>

配置文件中配置 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<NebulaAddress> 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<T> {
private Integer code;
private String message;
private List<T> data;

public boolean isSuccessed(){
return code == 0;
}
}
每次都是使用 Session 未免太麻烦,这里封装一个 NebulaTemplate 返回上面 对象 :

@Slf4j
@Component
public class NebulaTemplate {

@Resource
Session session;

public <T> NebulaResult<T> queryObject(String stmt, Class<T> tClass) {
NebulaResult<T> 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<JSONObject> 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<Info> infoNebulaResult = nebulaTemplate.queryObject(sql, Info.class);
return infoNebulaResult;
}
}




————————————————
版权声明:本文为CSDN博主「小毕超」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_43692950/article/details/124599111

相关文章