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

标签 java mongodb

如果条目不在数据库中,我有以下 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/

相关文章:

Node.js MongoDB 批量操作 UpdateOne 与 arrayFilters

java - 延迟加载对象集合以使用 HQL 插入

java - 如何为 Eclipse IDE 设置非 Eclipse Java 编译器

带有 FastAPI 的 MongoDb

node.js - mongoose.js 中的架构和子文档

c# - 无法使用 C# 驱动程序 1.10 连接到 MongoDB 3.0.0

java - 使用 JNI 将字符串数组从 java 传递到 C

java - 如何在 Tomcat 中为 Web 应用程序提供上下文配置?

java - Eclipse - 如何确定 Java 应用程序中的方法数

windows - 在 Windows 8.1 64 位上安装 MongoDB