当前位置: 首页 > 知识库问答 >
问题:

无法从java连接到本地mongoDB

王旺
2023-03-14
    null
public static void main(String[] args) {
        // connect to the local database server,default:127.0.0.1:27017
        MongoClient mongoClient = MongoClients.create();
        // get handle to "testDB" database
        MongoDatabase database = (MongoDatabase) mongoClient.getDatabase("testDB");
        SingleResultCallback<Void> callbackWhenFinished = new SingleResultCallback<Void>() {
            @Override
            public void onResult(final Void result, final Throwable t) {
                System.out.println("Operation Finished!");
            }
        };
        // get a handle to the "test" collection
        MongoCollection<Document> collection = database.getCollection("test");
        collection.insertOne(new Document("lala","hehe"),callbackWhenFinished);
    }

我确信我已经在127.0.0.1:27017启动了数据库服务,并且可以用shell和非异步方法连接。错误:

PrimaryServerSelector没有从群集描述中选择服务器ClusterDescription{type=unknown,connectionmode=single,all=[ServerDescription{address=localhost:27017,type=unknown,state=connecting}]}。超时前等待30000毫秒

共有1个答案

谷森
2023-03-14

我在自己的(正在运行的)MongoDB服务器上运行您的代码,可以看到相同的错误。但令我震惊的是,错误显示“在超时前等待30000ms”,但代码在不到30秒的时间内完成。这给出了一个问题的暗示。

请记住,这是异步的--因此,您不能期望所有操作都在同一线程上顺序运行。实际发生的情况是,main方法在对数据库的调用完成之前就已经完成了。

如果在终止之前更改代码以等待结果返回,则会得到更合理的结果。

public static void main(String[] args) throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    // connect to the local database server,default:127.0.0.1:27017
    MongoClient mongoClient = MongoClients.create();
    // get handle to "testDB" database
    MongoDatabase database = (MongoDatabase) mongoClient.getDatabase("testDB");
    SingleResultCallback<Void> callbackWhenFinished = new SingleResultCallback<Void>() {
        @Override
        public void onResult(final Void result, final Throwable t) {
            System.out.println("Operation Finished!");
            latch.countDown();
        }
    };
    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");
    collection.insertOne(new Document("lala", "hehe"), callbackWhenFinished);

    latch.await();
}
Aug 11, 2015 9:31:34 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Aug 11, 2015 9:31:35 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by PrimaryServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
Aug 11, 2015 9:31:35 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:4}] to localhost:27017
Aug 11, 2015 9:31:35 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 0, 2]}, minWireVersion=0, maxWireVersion=3, electionId=null, maxDocumentSize=16777216, roundTripTimeNanos=1281647}
Aug 11, 2015 9:31:35 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:5}] to localhost:27017
Operation Finished!
public static void main(String[] args) throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    // connect to the local database server,default:127.0.0.1:27017
    MongoClient mongoClient = MongoClients.create();
    // get handle to "testDB" database
    MongoDatabase database = mongoClient.getDatabase("testDB");
    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");

    collection.insertOne(new Document("lala", "hehe"),
                         (result, t) -> {
                             System.out.println("Operation Finished!");
                             latch.countDown();
                         });

    latch.await();
}
 类似资料:
  • 我试图连接到mysql数据库从docker图像。然而,这是投掷错误。 下面是我正在使用的docker图像。https://hub.docker.com/_/mysql/ 下面是我用来运行docker映像的命令。 以下是命令的输出 如果我使用docker检查IP并ping该IP,则显示IP不可访问。 如果我尝试使用和我遇到以下错误。 无法加载身份验证插件“缓存\u sha2\u密码”。

  • 我正在尝试使用rds部署带有MySQL引擎的rds实例。数据库子网组位于公用子网中。 我已执行以下检查:-允许安全组在端口3306上进行公共访问-在端口3306上的endpointURL上成功执行Telnet命令 配置如下: 日志记录详细信息: 正在尝试使用console连接到rds

  • 我试图连接到一个名为的数据库。所有凭据都位于PHP文件名中,格式为 我正试图用这个连接到数据库 我得到这个错误: 注意:第6行的未定义变量:DB_HOST in/home/content/06/8274306/html/beta/mysuperscript.php 注意:未定义变量:第6行 /home/content/06/8274306/html/beta/mysuperscript.phpDB

  • 我试图运行一个连接到本地独立spark集群的java应用程序。我使用start-all.sh以默认配置启动集群。当我转到集群的web页面时,它被启动为OK。我可以用SparkR连接到这个集群,但是当我使用相同的主URL从Java内部连接时,我会得到一条错误消息。 下面是Spark日志中的输出:

  • 试图连接一个简单的JMX监控。托管应用程序和监控工具位于同一台服务器上。当试图连接一个错误 00:30:55610致命http-8080-6 SiteListener:makeJmxConnection:99-java.io。IOException:检索RMIServer存根失败:javax.naming。ServiceUnavailableException[根异常为java.rmi.Conne

  • mongo admin--主机mongo1.xxxx.com--ssl--sslpemkeyfile mongoclient.pem--sslcafile mongoca.crt 不起作用 我从Mongo这边得到了这个错误: 我做错了什么?