嗨,我尝试在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();
答案 0 :(得分:0)
发现问题: 启动的两个嵌入式mongo实例未设置为副本集。要使用mongoClient,它们必须是副本集。
解决方案: 我在github上找到了解决方法:https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo/issues/257#issuecomment-427642563
这样,我可以启动彼此为副本集的mongo实例,并将其用于测试。