简体   繁体   中英

Problem trying to use seeds with MongoClient

Hi I have a problem when trying to use seeds with MongoClient in JAVA. When debuging I may look into the mongoClient and see that the servers is added in there, but once it tries to get the database I see this error:

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

Code building server list:

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

Client initiation as normal:

mongoClient = new MongoClient(serverAddresses);

And I try to get collection list like this:

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

It fails on db.listCollectionNames().

Note that when using a single ServerAddress this works, it is only when I add a second ServerAddress to the list that it fails.

The server address list listed from the mongoClient looks like this

[localhost:59508, localhost:59518]

So the adress and ports are there, I have tried to connect to the host Using Robo... and I may connect to them both.

Note that I use MongodForTestsFactory to create the 2 mongoDB instances.

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

Found problem: The two embeded mongo instances launched was not set to be replica sets. To work with mongoClient they must be replica sets.

Sollution: I found the sollution on github: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo/issues/257#issuecomment-427642563

With this I could launch mongo instances that was replica sets to each other and use them for my test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM