gpt4 book ai didi

java - 使用 Java 驱动程序在 Mongodb 中出现超时异常

转载 作者:行者123 更新时间:2023-12-02 05:13:33 25 4
gpt4 key购买 nike

如果条目不在数据库中,我有以下 Java 代码将新条目保存到 MongoDB。我在 Java Timer 中每 2 秒运行一次。

        MongoClient mongoClient = null;
try {
mongoClient = new MongoClient("localhost", 27017);
} catch (UnknownHostException e) {
e.printStackTrace();
}

DB db = mongoClient.getDB("testdb");

DBCollection coll = db.getCollection("testcollection");

// Search for existing entries

BasicDBObject query = new BasicDBObject("link", entry_url);

DBCursor cursor = coll.find(query);
try {
// If it is a new entry, insert
if (cursor.hasNext() == false) {
// Insert new entry
BasicDBObject doc = new BasicDBObject("link", entry_url)
.append("a_time", accept_time).append(
"p_time", formatter.format(date));
coll.insert(doc);
}
} finally {
cursor.close();
}

问题是几分钟后,出现com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting to connect。集群状态的客户端 View 是来自 mongoDB 的 {type=Unknown,servers=[{address=localhost:27017, type=Unknown, state=Connecting}]。它指的是cursor.hasNext()。对于这个问题有什么建议吗?

Exception in thread "Timer-0" com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting to connect. Client view of cluster state is {type=Unknown, servers=[{address=localhost:27017, type=Unknown, state=Connecting}]
at com.mongodb.BaseCluster.getDescription(BaseCluster.java:128)
at com.mongodb.DBTCPConnector.getClusterDescription(DBTCPConnector.java:396)
at com.mongodb.DBTCPConnector.getType(DBTCPConnector.java:569)
at com.mongodb.DBTCPConnector.isMongosConnection(DBTCPConnector.java:370)
at com.mongodb.Mongo.isMongosConnection(Mongo.java:623)
at com.mongodb.DBCursor._check(DBCursor.java:494)
at com.mongodb.DBCursor._hasNext(DBCursor.java:621)
at com.mongodb.DBCursor.hasNext(DBCursor.java:657)

定时器实现

         try {
Timer timer = new Timer();
timer.schedule(new STimer(), 0, 2 * 1000);
} catch (Exception e) {
e.printStackTrace();
}

根据下面的评论,我关闭了 mongoClient 连接。问题解决了。

最佳答案

您还必须确保 MongoClient 正确关闭

关于java - 使用 Java 驱动程序在 Mongodb 中出现超时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27151408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com