程序在Mongodb异步查询完成之前终止

时间:2015-12-29 02:26:05

标签: java mongodb asynchronous

我正在关注教程:http://mongodb.github.io/mongo-java-driver/3.2/driver-async/reference/crud/。我只是想连接到数据库并读取我用2个文档创建的集合:

import com.mongodb.async.SingleResultCallback;
import com.mongodb.async.client.MongoClient;
import com.mongodb.async.client.MongoClients;
import com.mongodb.async.client.MongoCollection;
import com.mongodb.async.client.MongoDatabase;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;

public class Main {

    MongoClient client = MongoClients.create();
    MongoDatabase database = client.getDatabase("mydb");

    public Main() {
        readUsers();
    }


    public void readUsers() {

        MongoCollection<Document> collection = database.getCollection("user");

        // find documents
        collection.find().into(new ArrayList<Document>(),
                new SingleResultCallback<List<Document>>() {
            @Override
            public void onResult(final List<Document> result, final Throwable t) {
                System.out.println("Found Documents: #" + result.size());
            }
        });
    }

    public static void main(String[] args) throws Exception {
        new Main();
    }

}

但我一直收到以下错误:

  

2015年12月28日下午6:22:51 com.mongodb.diagnostics.logging.JULLogger日志   信息:使用设置{hosts = [localhost:27017]创建的集群,   mode = SINGLE,requiredClusterType = UNKNOWN,   serverSelectionTimeout ='30000 ms',maxWaitQueueSize = 500} 2015年12月28日   下午6:22:51 com.mongodb.diagnostics.logging.JULLogger日志信息:没有   ReadPreferenceServerSelector选择的服务器{readPreference = primary}   来自群集描述ClusterDescription {type = UNKNOWN,   connectionMode = SINGLE,all = [ServerDescription {address = localhost:27017,   type = UNKNOWN,state = CONNECTING}]}。在计时之前等待30000毫秒   出

我不确定为什么会这样?我正在关注文档显示的内容。

2 个答案:

答案 0 :(得分:1)

Main()返回类似内容之前,您需要确保readUsers代码尚未完成:

...
import java.util.concurrent.Semaphore;

public class Main {
    MongoClient client = MongoClients.create();
    MongoDatabase database = client.getDatabase("mydb");
    Semaphore semaphore = new Semaphore(0);

    public Main() throws Exception {
        readUsers();
        semaphore.acquire();
    }


    public void readUsers() {

        MongoCollection<Document> collection = database.getCollection("users");

        // find documents
        collection.find().into(new ArrayList<Document>(),
                new SingleResultCallback<List<Document>>() {
                    @Override
                    public void onResult(final List<Document> result, final Throwable t) {
                        System.out.println("Found Documents: #" + result.size());
                        semaphore.release();
                    }
                });
    }

    public static void main(String[] args) throws Exception {
        new Main();
    }

}

答案 1 :(得分:0)

我遇到了类似的问题,发现这个答案解决了它:

Can't connect to local monogoDB from java