gpt4 book ai didi

java - 使用身份验证连接到 MongoDB 失败

转载 作者:可可西里 更新时间:2023-11-01 09:13:33 29 4
gpt4 key购买 nike

我在版本 3 中使用 MongoDB,我创建了一个名为“logMonitor”的数据库并创建了一个用户,如:

{
"_id" : "logMonitor.log",
"user" : "log",
"db" : "logMonitor",
"roles" : [
{
"role" : "readWrite",
"db" : "logMonitor"
}
]
}

当我使用用户“log”通过 shell 连接到数据库时,它返回成功,就像这样:

[jboss@chonggouapp mongodb]$ mongo logMonitor -u "log" -p "log"

MongoDB shell version: 3.0.6

connecting to: logMonitor

但是,使用以下代码通过 Java 连接失败。

    ServerAddress addr = new ServerAddress("10.46.20.65", 27017);

MongoCredential credential = MongoCredential.createMongoCRCredential(
"log", "logMonitor", "log".toCharArray());

MongoClientOptions options = MongoClientOptions.builder()
.serverSelectionTimeout(1000)
.build();
MongoClient mongoClient = new MongoClient(addr, Arrays.asList(credential), options);

MongoDatabase db = mongoClient.getDatabase("logMonitor");

long c = db.getCollection("sysLog").count();

引发了以下异常:

Exception in thread "main" com.mongodb.MongoTimeoutException: Timed out after 1000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=10.46.20.65:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSecurityException: Exception authenticating}, caused by {com.mongodb.MongoCommandException: Command failed with error 18: 'auth failed' on server 10.46.20.65:27017. The full response is { "ok" : 0.0, "errmsg" : "auth failed", "code" : 18 }}}]
at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:370)
at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:101)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71)
at com.mongodb.binding.ClusterBinding.getReadConnectionSource(ClusterBinding.java:63)
at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:65)
at com.mongodb.operation.CountOperation.execute(CountOperation.java:172)
at com.mongodb.operation.CountOperation.execute(CountOperation.java:43)
at com.mongodb.Mongo.execute(Mongo.java:738)
at com.mongodb.Mongo$2.execute(Mongo.java:725)
at com.mongodb.MongoCollectionImpl.count(MongoCollectionImpl.java:167)
at com.mongodb.MongoCollectionImpl.count(MongoCollectionImpl.java:147)
at com.baosight.bsfc4.mn.lg.utils.Test.main(Test.java:34)

谁能告诉我这是什么问题?我的 Java 代码有问题吗?

谢谢。

最佳答案

请改用 createMongoCredential(),它会为您创建正确类型的凭据。

关于java - 使用身份验证连接到 MongoDB 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34414406/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com