我使用 mongo-java-driver 3.1.0。与JAVA和MongoDB连接没有问题。我可以使用JAVA从MongoDB获取数据并将数据写入MongoDB。
但是当我尝试写入更多数据时,我的 java 控制台上出现此错误。我认为当套接字连接持续超过 30 秒时,MongoDB 客户端就会崩溃。直到 30 秒,部分数据被插入到 MongoDB (myCollection) 首先我得到;
com.mongodb.MongoSocketReadException: Prematurely reached end of stream
然后
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}
我没有设置任何超时,因此它的超时应该是无穷大。
谁能帮忙
public void writeDB() {
MongoClient mongoClient = new MongoClient ("127.0.0.1", 27017);
mongoClient.setWriteConcern(WriteConcern.JOURNALED);
DB database = mongoClient.getDB("myCollection");
BasicDBObject newDataObject = new BasicDBObject();
DBCollection collection = database.getCollection("myCollection");
int number = 0;
for (int i = 0; i <= 1000000; i++) {
if(CHECKDATA_EXIST) {
int randomCount = (10 + (Math.random() * 300));
for (int j = 0; j < randomCount; j++) {
number = i + randomCount;
}
newDataObject.put("_id", i);
newDataObject.put("myNumber", number);
collection.insert(newDataObject);
}
}
}
顺便说一句,粉碎之后我无法再写入或获取任何数据。要写入数据,我必须重新启动“mongod”。
我为 if 情况添加了 CHECKDATA_EXIST 方法(我的代码包括该方法)。我忘了补充一点。该方法检查 id 是否存在。
最佳答案
嗨,我有一段时间遇到同样的问题,然后我发现了这个 http://3t.io/blog/how-to-prevent-your-connection-from-dropping-with-hosted-mongodb-instances/
它表示连接可能会在短时间不活动后断开,但当您尝试再次连接时会恢复连接。
如果您的代码是长时间运行的应用程序,我建议您进行如下更改: 更改连接构造函数添加 MongoClientOptions
public void writeDB() {
MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
//build the connection options
builder.maxConnectionIdleTime(60000);//set the max wait time in (ms)
MongoClientOptions opts = builder.build();
<strike>MongoClient mongoClient = new MongoClient ("127.0.0.1", 27017);</strike>
MongoClient mongoClient = new MongoClient ("127.0.0.1:27017", opts);
mongoClient.setWriteConcern(WriteConcern.JOURNALED);
DB database = mongoClient.getDB("myCollection");
BasicDBObject newDataObject = new BasicDBObject();
DBCollection collection = database.getCollection("myCollection");
int number = 0;
for (int i = 0; i <= 1000000; i++) {
if(CHECKDATA_EXIST) {
int randomCount = (10 + (Math.random() * 300));
for (int j = 0; j < randomCount; j++) {
number = i + randomCount;
}
newDataObject.put("_id", i);
newDataObject.put("myNumber", number);
collection.insert(newDataObject);
}
}
}
希望这会有所帮助
关于java - "com.mongodb.MongoSocketReadException"和 "com.mongodb.MongoTimeoutException"的解决方案是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33008514/