MongoDB: No server chosen by ReadPreferenceServerSelector

来源:互联网 发布:现在有5g网络吗 编辑:程序博客网 时间:2024/05/17 04:56

关于此问题做项纪录:

解决问题方法来自:MongoDB: No server chosen by ReadPreferenceServerSelector

首先出问题的代码块

MongoClient connection = MongoClients.create("mongodb://localhost:27017");        MongoDatabase testDatabase = connection.getDatabase("test");        MongoCollection<Document> bankcards = testDatabase.getCollection("bank_card");FindIterable<Document> bcs = bankcards.find();bcs.forEach(document -> {            System.out.println("eid === " + document.getString("eid") + ",name === " + document.getString("name"));        }, (aVoid, throwable) -> {            if (null != throwable) {                System.out.println("error ===> " + throwable);            }        });

在内部连接池尝试与MongoDB连接的时候,MongoClient并不会阻塞等待。 默认时间serverSelectionTimeout 30000ms。
此处回调并未做任何处理。 如果你添加一个锁,然后等待响应,然后你会看到回调被调用例如:

final CountDownLatch latch = new CountDownLatch(1);SingleResultCallback<Void> callbackWhenFinished = (result, t) -> {            System.out.println("Operation Finished!");            if (t != null) {                System.out.println("listDatabaseNames() errored: " + t.getMessage());            }            latch.countDown();        };        bcs.forEach(document -> {            System.out.println("eid === " + document.getString("eid") + ",name === " + document.getString("name"));        }, callbackWhenFinished);        latch.await();

现在使用锁存器我们await()直到回调被调用,现在我们应该看到两件事情:

1.没有MongoDB可用。 它最终将调用回调并打印出有错误。 它将等待,直到serverSelectionTimeout超时。
2.有一个MongoDB可用。 它将最终连接,对于每个数据库,它将应用Block并打印出数据库名称,然后最终它将调用已完成的回调信号。

0 0
原创粉丝点击