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

使用JDBC连接到云中托管的MongoDB时出错

梁巴英
2023-03-14

我正在尝试使用JDBC连接到托管在云中的MongoDB。但是,认证失败。

My development environment:

Mac OSX
Eclipse

Drivers:

junit-3.8.1.jar
mongodb-driver-3.2.2.jar
mongodb-driver-core-3.2.2.jar
bson-3.2.2.jar


I'm using the driver as suggested by the below url:

http://mongodb.github.io/mongo-java-driver/?_ga=1.221045400.1622521490.1456732063

Actually, the drivers are updated by the below dependency declaration, by maven build:

     
    org.mongodb 
    mongodb-driver 
    3.2.2 
    

以下是我的Java代码:

private static void test() {


    String url = "mongodb://user:pwd@host:19468/heroku_dbname";
    MongoClient mongoClient = new MongoClient(new MongoClientURI(url));


    // get handle to "heroku_dbname" database
    MongoDatabase database = mongoClient.getDatabase("heroku_dbname");


    // get a handle to the "book" collection
    MongoCollection<Document> collection = database.getCollection("book");

    // make a document and insert it
    Document doc = new Document("title", "Good Habits")
                   .append("author", "Akbar");

    collection.insertOne(doc);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    Document myDoc = collection.find().first();
    System.out.println(myDoc.toJson());

    // release resources
    mongoClient.close();
}

当我执行时,我得到以下异常:

Mar 17, 2016 7:15:31 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[ds019468.mlab.com:19468], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Mar 17, 2016 7:15:31 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by WritableServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=ds019468.mlab.com:19468, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
Mar 17, 2016 7:15:33 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Exception in monitor thread while connecting to server ds019468.mlab.com:19468
com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName='db_userName', source='heroku_dbName', password=, mechanismProperties={}}
    at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:61)
    at com.mongodb.connection.DefaultAuthenticator.authenticate(DefaultAuthenticator.java:32)
    at com.mongodb.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:99)
    at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:44)
    at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
    at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:128)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server ds019468.mlab.com:19468. The full response is { "ok" : 0.0, "code" : 18, "errmsg" : "Authentication failed." }
    at com.mongodb.connection.CommandHelper.createCommandFailureException(CommandHelper.java:170)
    at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:123)
    at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32)
    at com.mongodb.connection.SaslAuthenticator.sendSaslStart(SaslAuthenticator.java:95)
    at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:45)
    ... 6 more

Exception in thread "main" com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches WritableServerSelector. Client view of cluster state is {type=UNKNOWN, servers=[{address=ds019468.mlab.com:19468, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName='db_userName', source='heroku_dbName', password=, mechanismProperties={}}}, caused by {com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server ds019468.mlab.com:19468. The full response is { "ok" : 0.0, "code" : 18, "errmsg" : "Authentication failed." }}}]
    at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:369)
    at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:101)
    at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.(ClusterBinding.java:75)
    at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.(ClusterBinding.java:71)
    at com.mongodb.binding.ClusterBinding.getWriteConnectionSource(ClusterBinding.java:68)
    at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:219)
    at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:168)
    at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:74)
    at com.mongodb.Mongo.execute(Mongo.java:781)
    at com.mongodb.Mongo$2.execute(Mongo.java:764)
    at com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:515)
    at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:306)
    at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:297)
    at com.chozhan.test.mongodb.MongoJdbcRemote.test(MongoJdbcRemote.java:64)
    at com.chozhan.test.mongodb.MongoJdbcRemote.main(MongoJdbcRemote.java:43)

我能够通过mLab web界面以相同的用户id和密码成功登录,并且工作正常。

但是,只有JDBC尝试失败。

有人能帮忙吗,这里有什么问题?

共有3个答案

公羊瀚
2023-03-14

对我有效的是在应用程序中更改URL。属性:

spring.data.mongodb.uri=mongodb://username:password@host:port/database_name

到:

spring.data.mongodb.uri=mongodb+srv://username:password@host:port/database?retryWrites=true&w=majority

我读到,**MongoDB**默认数据库是test。在我的应用程序中,我将host:port替换为从mongodb获得的URI。com,尽管URL不包含端口的值,但它仍然可以工作。

陆洛城
2023-03-14

这个问题由mLab支持解决。我用的是mLab的"网页界面用户ID密码"。有人建议我创建一个单独的数据库用户id/密码来连接。它可以使用新创建的db用户id/密码。

潘高岑
2023-03-14

创建客户端连接时,需要添加身份验证详细信息。

MongoCredential credential = MongoCredential.createCredential(user, heroku_dbname, pwd);
MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential));

或者只需更新您的URL:

MongoClientURI uri = new MongoClientURI("mongodb://user1:pwd1@host1/?authSource=db1");
 类似资料:
  • 我尝试通过腻子连接,它工作正常。我不明白如何添加 pem 文件路径和用户名以通过 java 登录到 Mongo 外壳 MongoClient mongoClient = new MongoClient( “ec2-xx-xx-xxx-xx.xx-xxxx-1.xxxxxx.amazonaws.com” , 27017 );DB db = mongoClient.getDB(“userDB”);

  • 我们所面临的问题已在许多文件中得到充分证明https://stackoverflow.com/questions/34189756/warning-about-ssl-connection-when-connecting-to-mysql-database. 从过渡到时,我们就开始面临这个问题。建议的修复方法对我们有效,但我们有一个问题,我们不想更新Java源文件以进行更改,例如从 到 正如在ht

  • 下面是/etc/kafka/connect-MongoDB-source.properties中的MongoDB配置 但是低于误差 以独立模式运行连接器。 我在debezium-debezium-连接器-mongob-1.0.0/debezium-connector-mongodb-1.0.0.Final.jar 类路径的设置如下 使用插件路径,我看到它能够注册和加载所有必需的插件。 但最后还是同

  • 我目前正在通过以下教程学习如何通过mongodb API使用Azure的cosmosdb:https://docs.microsoft.com/en-us/azure/cosmos-db/tutorial-develop-mongoDB-react 本教程的最终repo在这里:https://github.com/azure-samples/react-cosmosdb,但到目前为止,我只是在第5

  • 所以我把这个oracle数据库托管在Linux服务器上。我知道如何从windows机器上使用putty访问它,但我需要从windows机器上使用JDBC访问它。我有数据库的主机名、端口、服务名、用户名和密码。我不知道如何打开连接。我试过这样: 但我无法接通请帮帮忙 编辑: 好的,我意识到地址是错误的,所以我把它改为:Connection con=DriverManager.getConnectio

  • 我是nodejs和MongoDB的重要成员。尝试连接到数据库时遇到以下错误: (节点:10124)UnhandledPromiseRejectionWarning:MongoNetworkError:在池上第一次连接[MongoNetworkError:connect Econnn拒绝127.0.0.1:27017]时无法连接到服务器[127.0.0.1:27017].(E:\node js wo