[英]Problem trying to use seeds with MongoClient
嗨,我嘗試在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();
發現的問題:啟動的兩個嵌入式mongo實例未設置為副本集。 要使用mongoClient,它們必須是副本集。
解決方案:我在github上找到了解決方案: https : //github.com/flapdoodle-oss/de.flapdoodle.embed.mongo/issues/257#issuecomment-427642563
這樣,我可以啟動相互為副本集的mongo實例,並將其用於測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.