SpringBoot入门系列(十二)springboot加nebula

背景

nebula做为高性能图数据库,在实际生产里越用越多,怎么用springboot接入呢?

版本约定

  • nebula 2.6.0
  • nebula client 2.6.0
  • springboot 2.1.6.RELEASE

代码部分

配置文件

<!-- 最核心的部分 -->
<dependency>
    <groupId>com.vesoft</groupId>
    <artifactId>client</artifactId>
    <version>2.6.0</version>
</dependency>

配置项

nebula:
  address[0]:
    host: xx.x.xxx.x
    port: 9669
  username: test
  password: 123
  reconnect: false
  space: yourspace

java部分

常量

import lombok.AllArgsConstructor;
import lombok.Getter;

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

映射nebula的地址和端口

import lombok.Data;

/**
 * @Desc
 **/
@Data
public class NebulaAddress {
    private String host;
    private Integer port;
}

自动装配属性

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @Desc
 **/
@Data
@Configuration
@ConfigurationProperties(prefix = "nebula")
public class NebulaProperties {
    private List<NebulaAddress> address;
    private String username;
    private String password;
    private boolean reconnect;
    private String space;
}

configuartion定义bean

import com.vesoft.nebula.client.graph.NebulaPoolConfig;
import com.vesoft.nebula.client.graph.data.HostAddress;
import com.vesoft.nebula.client.graph.net.NebulaPool;
import com.vesoft.nebula.client.graph.net.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;

import java.util.stream.Collectors;

@Slf4j
@Configuration
public class NebulaConfig {

    @Bean
    public NebulaPool nebulaPool(NebulaProperties nebulaProperties) throws Exception {
        NebulaPool pool = new NebulaPool();
        NebulaPoolConfig nebulaPoolConfig = new NebulaPoolConfig();
        // 最大连接数根据需要调整
        nebulaPoolConfig.setMaxConnSize(10);
        boolean init = pool.init(nebulaProperties.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 nebulaProperties) {
        try {
            Session session = nebulaPool.getSession(nebulaProperties.getUsername(), nebulaProperties.getPassword(), nebulaProperties.isReconnect());
            session.execute(String.format("%s %s%s", NebulaConstant.USE, nebulaProperties.getSpace(), NebulaConstant.SEMICOLON));
            return session;
        } catch (Exception e) {
            log.error("get nebula session err , {} ", e.toString());
        }
        return null;
    }
}

实际查询

@Service
@Slf4j
public class NebulaService {
	@Resource
    private Session session;

	private static final String[] COLUMNS = new String[] {"c1", "c2"};

	public List<JSONObject> searchByNgql(String ngql)  throws IOErrorException, UnsupportedEncodingException {
		ResultSet resultSet = Objects.requireNonNull(session).execute(ngql);
		return parseRes(resultSet);
	}
	
	private List<JSONObject> parseRes(ResultSet resultSet)  throws UnsupportedEncodingException {
		if (resultSet.isSucceeded()) {
			Map<String, List<ValueWrapper>> map = Maps.newHashMap();
			for (String col : COLUMNS) {
				List<ValueWrapper> values = resultSet.colValues(col);
				map.put(col, values);
			}
			// 把map转成你要的形式即可
		}
	}
	
}

须知

  • nebula客户端版本和目标库版本必须符合,不然nebula会拒绝访问

OVER

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值