SpringBoot multipleRepositories <>多个数据库集群

问题描述

我已经搜索过Spring多mongo配置,this article帮助了我。

  1. 作为扩展,我需要帮助来配置具有不同IP的集群mongodb。这是我的本地样本。

如何在此处添加多个主机?

    mongodb:
  content:
    uri: mongodb://localhost:27017/contents
  genre:
    uri: mongodb://localhost:27017/genres

解决方法

您可以添加用uri分隔的集群逗号服务器

uri: mongodb://username:password@server1:port,server2:port/database
,

您可以尝试根据应用配置设置加载不同数据源(Mongo 数据库集群)的其他选项。

实现 onReady @EventListener 并在启动 SpringBoot 应用程序时加载所有数据库集群。

在 onReady 内部根据如下配置创建所有数据源并存储在 Map 中

HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setJdbcUrl(url);
        hikariConfig.addDataSourceProperty("url",url);
        hikariConfig.addDataSourceProperty("user",username);
        hikariConfig.addDataSourceProperty("password",password);
        com.zaxxer.hikari.HikariDataSource hikariDataSource = new com.zaxxer.hikari.HikariDataSource(hikariConfig);

// Now lets store the hikariDataSource to a Map (dataSourcesMap)
try (Connection c = hikariDataSource.getConnection()) {
     dataSourcesMap.put(uniqueDBId,hikariDataSource);
}

我过去在许多连接多个数据库的 SpringBoot 应用程序中成功地使用 Postgres 和 MySQL 数据库实现了这一点。

,

对于可能是第一次来添加更多细节的人

官方文档:https://mongodb.github.io/mongo-java-driver/3.7/driver/tutorials/connect-to-mongodb/

错误:

 -     uri: mongodb://localhost:27017/contents,mongodb://un:pw@host1:27017/contents,mongodb://host2:27017/contents,mongodb://host3:27017/contents

对:

 -     uri: mongodb://un:pw@primaryhost:27017/contents

我仍在分析它如何选择副本集。但它对我有用。