Java 1636次插入后MongoDB引发超时异常
因此,我在Mongo中遇到了这个问题:我有一个java程序,可以将文档插入Mongo,数据是从一个名为“Article”的java对象中提取的,它的结构简化了,没有getter、setter、equals等:Java 1636次插入后MongoDB引发超时异常,java,mongodb,exception,timeout,Java,Mongodb,Exception,Timeout,因此,我在Mongo中遇到了这个问题:我有一个java程序,可以将文档插入Mongo,数据是从一个名为“Article”的java对象中提取的,它的结构简化了,没有getter、setter、equals等: public class Article { private String title; private String doi; private String country; private String date; private ArrayL
public class Article {
private String title;
private String doi;
private String country;
private String date;
private ArrayList<String> authors;
private ArrayList<String> references;
}
我真的被这个错误缠住了。任何帮助都将不胜感激。
谢谢 好的,刚刚发现问题所在,我忘了添加“mongoClient.close()”,所以最终失败了。一些评论:您只应该连接MongoDB一次,然后重新使用连接。Java MongoDB客户端附带自动连接池。第二,对于涉及大量文档的操作,应该使用,特别是对于插入。但是,您应该每隔大约10k次操作调用
.execute()
,以防止RAM的过度使用。最后但并非最不重要的一点是,对于我看到的数据模型,我想知道您是否最好使用图形数据库。非常感谢,我会考虑您的评论。
public static void saveArticle(Article article) {
MongoClient mongoClient = new MongoClient("localhost",27017);
MongoDatabase database = mongoClient.getDatabase("bibliometricDB");
MongoCollection<Document> collection = database.getCollection("papers");
Document doc = new Document("doi",article.getDoi())
.append("date", article.getDate())
.append("title", article.getTitle())
.append("country", article.getCountry())
.append("authors", article.getAuthors())
.append("references", article.getReferences());
collection.insertOne(doc);
}
}
Exception in thread "main" com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketReadException: Prematurely reached end of stream}}]
at com.mongodb.internal.connection.BaseCluster.getDescription(BaseCluster.java:179)
at com.mongodb.internal.connection.SingleServerCluster.getDescription(SingleServerCluster.java:41)
at com.mongodb.client.internal.MongoClientDelegate.getConnectedClusterDescription(MongoClientDelegate.java:136)
at com.mongodb.client.internal.MongoClientDelegate.createClientSession(MongoClientDelegate.java:94)
at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.getClientSession(MongoClientDelegate.java:249)
at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.execute(MongoClientDelegate.java:172)
at com.mongodb.client.internal.FindIterableImpl.first(FindIterableImpl.java:198)