【问题标题】:Problem trying to use seeds with MongoClient尝试将种子与 MongoClient 一起使用时出现问题
【发布时间】:2019-02-28 12:55:19
【问题描述】:

您好,我在 JAVA 中尝试通过 MongoClient 使用种子时遇到问题。调试时,我可能会查看 mongoClient 并看到服务器已添加到其中,但是一旦它尝试获取数据库,我就会看到此错误:

Caused by: com.mongodb.MongoTimeoutException: Timed out after 15000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN, servers=[]

代码构建服务器列表:

private List<ServerAddress> getListOfServerAddresses() throws Exception {
    List<ServerAddress> serverAddresses = new ArrayList<>();
    instancesJsonList = "[{\"host\":\"localhost\",\"port\":12345},{\"host\":\"localhost\",\"port\":54321}]\"}]";
    if (instancesJsonList != null) {
        final ObjectMapper mapper = new ObjectMapper();
        final JsonNode instanceList = mapper.readTree(instancesJsonList);
        for (final JsonNode node : instanceList) {
            final String host = node.get("host").asText();
            final String port = node.get("port").asText();

            ServerAddress address = new ServerAddress(host, Integer.parseInt(port));
            serverAddresses.add(address);
        }
    }
    return serverAddresses;
}

正常启动客户端:

mongoClient = new MongoClient(serverAddresses);

我尝试获取这样的收藏列表:

MongoDatabase db = mongoClient.getDatabase("My_database");
List<String> collectionList = db.listCollectionNames().into(new ArrayList<String>());

db.listCollectionNames() 失败。

请注意,当使用单个 ServerAddress 时,这是可行的,只有当我将第二个 ServerAddress 添加到列表中时,它才会失败。

从 mongoClient 列出的服务器地址列表如下所示

[localhost:59508, localhost:59518]

所以地址和端口都在那里,我尝试使用 Robo 连接到主机...我可能会同时连接到它们。

请注意,我使用 MongodForTestsFactory 创建 2 个 mongoDB 实例。

MongodForTestsFactory primaryTestsFactory = MongodForTestsFactory.with(Version.V3_4_1);
mongoClientPrimary = primaryTestsFactory.newMongo();
primaryPort = mongoClientPrimary.getAddress().getPort();

【问题讨论】:

    标签: java mongodb


    【解决方案1】:

    发现问题: 启动的两个嵌入式 mongo 实例未设置为副本集。要使用 mongoClient,它们必须是副本集。

    解决办法: 我在github上找到了解决方案:https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo/issues/257#issuecomment-427642563

    有了这个,我可以启动相互复制的 mongo 实例,并将它们用于我的测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      • 2014-05-17
      • 2012-11-26
      • 1970-01-01
      • 2011-03-15
      • 2011-05-27
      • 1970-01-01
      相关资源
      最近更新 更多