【发布时间】: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();
【问题讨论】: