我使用mongo-java-driver 3.1.0。与JAVA和MongoDB的连接没有问题。我可以从MongoDB中获取数据,并使用JAVA将数据写入MongoDB。
但是当我尝试写更多的数据时,我在java控制台上得到这个错误。我认为当套接字连接持续超过30秒,MongoDB客户端崩溃。直到30秒的数据的一部分插入到MongoDB (myCollection)首先我得到;
com.mongodb。monsocketreadeexception:过早到达结束流
和
com.mongodb。mongomeoutexception:在30000毫秒后超时等待与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"。
我添加了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);
}
}
}
希望对大家有所帮助
在你的代码中,你在循环中插入单个文档,所以不要使用批量发送每个文档,修改你的代码。
检查下面的代码片段:
DBCollection collection = database.getCollection("myCollection");
BulkWriteOperation bulkWriteOperation= collection.initializeUnorderedBulkOperation();
for (int i = 0; i <= 1000000; i++) {
BasicDBObject newDataObject = new BasicDBObject();
IncrementalStat incrementalStat = new IncrementalStat();
double randomCount = (10 + (Math.random() * 300));
for (int j = 0; j < randomCount; j++) {
number = i + randomCount;
}
newDataObject.put("_id", i);
newDataObject.put("myNumber", number);
bulkWriteOperation.insert(newDataObject);
}
//write all data using bulk execute
BulkWriteResult result=bulkWriteOperation.execute();