使用Java驱动程序在Mongodb中超时异常

时间:2014-11-26 14:17:36

标签: java mongodb

如果条目不在DB中,我有以下Java代码来保存MongoDB的新条目。我每隔2秒在Java Timer中运行它。

        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();
        }

问题是几分钟后,mongoDB中有一个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}]。它指的是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连接。问题解决了。

1 个答案:

答案 0 :(得分:2)

您还必须确保MongoClient已正确关闭

相关问题