当前位置: 首页 > article >正文

NebulaGraph学习笔记-自定义SessionPool

最近看了一下NebulaGraph图数据库连接的部分资料,发现还可以通过SessionPool的方式连接。下面是一个简单的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.8.4</version>
</dependency>
  • NebulaGraph连接属性类
@Data
@ConfigurationProperties(prefix = "nebula-graph")
public class NebulaGraphProperties {

	/** 集群节点 */
	private String[] clusterNodes = null;

	/** 用户名 */
	private String username;

	/** 密码 */
	private String password;

	private List<CSessionPoolConfig> cSessionPoolConfigs = new ArrayList<>();

	@Data
	public static class CSessionPoolConfig {
		/** 空间名称 */
		private String spaceName;

		/** 最小Session数 */
		private int minSessionSize = 10;

		/** 最大Session数 */
		private int maxSessionSize = 100;

		/** 是否重连 */
		private boolean reconnect = true;

		/** Timeout */
		private int timeout = 0;

		/** WaitTime */
		private int waitTime = 0;

		/** CleanTime */
		private int cleanTime = 3600;

		/** IntervalTime */
		private int intervalTime = 0;

		/** Health Check Time */
		private int healthCheckTime = 600;

		/** Retry Connect Times */
		private int retryConnectTimes = 1;

		/** Retry Times */
		private int retryTimes = 3;

	}

}
  • SessionPoolBeanDefinitionRegistrar类
public class SessionPoolBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {

    private NebulaGraphProperties nebulaGraphProperties;

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        if (ObjectUtil.isNull(nebulaGraphProperties)) {
            return;
        }

        List<NebulaGraphProperties.CSessionPoolConfig> cSessionPoolConfigs = nebulaGraphProperties.getCSessionPoolConfigs();
        if (cSessionPoolConfigs.isEmpty()) {
            return;
        }

        List<HostAddress> hostAddresses = new ArrayList<>();
        String[] clusterNodes = nebulaGraphProperties.getClusterNodes();
        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])));
        }

        String username = nebulaGraphProperties.getUsername();
        String password = nebulaGraphProperties.getPassword();

        cSessionPoolConfigs.forEach(cSessionPoolConfig -> {
            String spaceName = cSessionPoolConfig.getSpaceName();
            if (CharSequenceUtil.isBlank(spaceName)) {
                return;
            }
            SessionPoolConfig sessionPoolConfig = new SessionPoolConfig(hostAddresses, spaceName, username, password);
            sessionPoolConfig.setMinSessionSize(cSessionPoolConfig.getMinSessionSize());
            sessionPoolConfig.setMaxSessionSize(cSessionPoolConfig.getMaxSessionSize());
            sessionPoolConfig.setTimeout(cSessionPoolConfig.getTimeout());
            sessionPoolConfig.setWaitTime(cSessionPoolConfig.getWaitTime());
            sessionPoolConfig.setCleanTime(cSessionPoolConfig.getCleanTime());
            sessionPoolConfig.setIntervalTime(cSessionPoolConfig.getIntervalTime());
            sessionPoolConfig.setHealthCheckTime(cSessionPoolConfig.getHealthCheckTime());
            sessionPoolConfig.setRetryConnectTimes(cSessionPoolConfig.getRetryConnectTimes());
            sessionPoolConfig.setRetryTimes(cSessionPoolConfig.getRetryTimes());
            sessionPoolConfig.setReconnect(cSessionPoolConfig.isReconnect());

            RootBeanDefinition rootBeanDefinition = new RootBeanDefinition();
            rootBeanDefinition.setBeanClass(SessionPool.class);
            rootBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue(sessionPoolConfig);
            beanDefinitionRegistry.registerBeanDefinition(String.format("%sSessionPool", spaceName), rootBeanDefinition);
        });
    }

    @Override
    public void setEnvironment(Environment environment) {
        BindResult<NebulaGraphProperties> bindResult = Binder.get(environment)
            .bind(nebulaGraphPropertiesPrefix(), NebulaGraphProperties.class);
        if (ObjectUtil.isNotNull(bindResult) && bindResult.isBound()) {
            nebulaGraphProperties = bindResult.get();
        }
    }

    private String nebulaGraphPropertiesPrefix() {
        return Objects.requireNonNull(
            AnnotationUtils.getAnnotation(NebulaGraphProperties.class, ConfigurationProperties.class)).prefix();
    }

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

}
  • 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:
  cluster-nodes:
    - 192.168.0.1:9559
    - 192.168.0.1:9669
  username: root
  password: 123456
  c-session-pool-configs:
    - space-name: tmp1_space_name
      min-session-size: 10
      max-session-size: 200
  • 项目引入部分代码
@Slf4j
@Service("nebulaGraphService")
public class NebulaGraphServiceImpl implements NebulaGraphService {

    @Autowired
    private SessionPool sessionPool;
	
	protected String executeJsonWithParameter(String statement, Map<String, Object> paramsMap)
            throws ClientServerIncompatibleException, AuthFailedException, BindSpaceFailedException, IOErrorException {
        return sessionPool.executeJsonWithParameter(statement, paramsMap);
    }

}
总体来说也是比较简单的。

http://www.kler.cn/a/470465.html

相关文章:

  • Android存储方案对比(SharedPreferences 、 MMKV 、 DataStore)
  • pytorch中nn.Conv2d详解及参数设置原则
  • 十年后LabVIEW编程知识是否会过时?
  • 面向对象分析与设计Python版 活动图与类图
  • 【SOC 芯片设计 DFT 学习专栏 -- ATE 测试中 at-speed 测试】
  • 在线机考|2024华为实习秋招春招编程题(最新)——第3题_个性化歌单推荐系统_300分(十一)
  • 「Mac畅玩鸿蒙与硬件52」UI互动应用篇29 - 模拟火车票查询系统
  • 系统思考—变革之舞
  • 【C++】1139:整理药名
  • garak - 开源的 LLMs 漏洞扫描工具
  • Windows系统下FFmpeg4.4的环境搭建(二)
  • 基于 Python 的大学教室资源管理系统的设计与实现
  • Edge SCDN高效防护与智能加速
  • jenkins入门3 --执行一个小demo
  • Lua语言的语法糖
  • rtsp rtp:missed 1 packects
  • 使用插件生成 Mybatis 实体类及接口
  • 深度解析Linux中的make/Makefile的使用方法
  • 算法的学习笔记—不用常规控制语句求 1 到 n 的和
  • Innodisk iSMART V6使用说明_SSD还能用多久?已经读写了多少次数?……
  • 依据多波段栅格数据进行建筑统计操作(基于ArcGIS操作)
  • Nginx linux安装步骤(超详细)
  • Flink DataSet API
  • 数据结构 - inode
  • 三甲医院等级评审八维数据分析应用(六)--数据安全与隐私保护篇
  • Python多分类Logistic回归详解与实践