MongoDB + Azure + Android:错误:com.mongodb.MongoException:不与master交谈,重试用完了

时间:2013-12-07 03:57:43

标签: java android mongodb azure mongodb-java

背景

我使用mongo-azure library在Azure云服务工作者+ Web角色中运行MongoDB副本集。我第一次设置我的Android项目连接到MongoDB / Azure时,IO(读取和写入)工作。然后,由于我的硬编码测试JSONString中的拼写错误,我崩溃了应用程序,因此Mongo实例无法正常关闭。修复JSONString问题后,我收到以下错误(在堆栈跟踪中)并且无法访问MongoDB / Azure。也许没有正确关闭连接导致错误?

问题

这个错误究竟是什么意思?为什么主实例不可用?

E/AndroidRuntime: com.mongodb.MongoException: not talking to master and retries used up

完整堆栈跟踪

E/AndroidRuntime(6274): FATAL EXCEPTION: Thread-7108
E/AndroidRuntime(6274): Process: com.myproject.examplemongodb, PID: 6274
E/AndroidRuntime(6274): com.mongodb.MongoException: not talking to master and retries used up
E/AndroidRuntime(6274):     at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:271)
E/AndroidRuntime(6274):     at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:273)
E/AndroidRuntime(6274):     at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:273)
E/AndroidRuntime(6274):     at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:216)
E/AndroidRuntime(6274):     at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:288)
E/AndroidRuntime(6274):     at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:273)
E/AndroidRuntime(6274):     at com.mongodb.DB.getCollectionNames(DB.java:400)
E/AndroidRuntime(6274):     at com.myproject.examplemongodb.ActivityMain$1.run(ActivityMain.java:89)
E/AndroidRuntime(6274):     at java.lang.Thread.run(Thread.java:841)

备注

  • 我使用的是最新的mongo-java-driver(目前为2.11.3)。
  • 我正在远程连接数据库(非本地主机)。
  • 另一个question提到了这个错误,但OP正在使用不同的驱动程序,他的解决方案不适用于Android / Java。

可能的解决方案

  • 似乎从应用程序关闭连接允许下一次运行正常工作。但是,我仍然担心能够允许并发连接,我肯定会这样做。
    • 更新:我已经包装了一个mongodb登录并注销了我的每个查询到服务器,但错误似乎仍然间歇性地出现。到目前为止,似乎每次都写作,但只读取工作的一半时间。另一半时间是发布的错误。

1 个答案:

答案 0 :(得分:2)

间歇性错误的原因是驱动程序的默认读取首选项,主要是副本集。默认读取首选项是主要的。对于下面提到的每种模式,PRIMARY指的是主数据库(始终是最新的),SECONDARY指的是slave(s),它们基本上是master的副本,并不总是最新的。

PRIMARY: The default read mode. Read from primary only. Throw an error if
         primary is unavailable. Cannot be combined with tags.

将读取首选项更改为以下之一的解决方案:

PRIMARY PREFERRED: Read from primary if available, otherwise a secondary.
SECONDARY PREFERRED: Read from a secondary if available, otherwise read from the primary.
NEAREST: Read from any member node from the set of nodes which respond the fastest.

示例代码:

// Use this when doing a read if you don't care if the data is always consistent.
// Change the following with secondaryPreferred() if you have high writes, so
// that you don't interfere with them.
ReadPreference preference = ReadPreference.primaryPreferred();
DBCursor cur = new DBCursor(collection, query, null, preference);

有关详细信息,请参阅source