Timed out after 30000 ms while w

2019-10-13  本文已影响0人  秋元_92a3

今天使用mongo-java-drive写连接mongo的客户端,着实被上面那个错坑了一把。回顾一下解决过程:

报错:

com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketWriteException: Exception sending message}, caused by {javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake}, caused by {java.io.EOFException: SSL peer shut down incorrectly}}]
    at com.mongodb.connection.BaseCluster.getDescription(BaseCluster.java:167)
    at com.mongodb.client.internal.MongoClientDelegate.getConnectedClusterDescription(MongoClientDelegate.java:106)
    at com.mongodb.client.internal.MongoClientDelegate.createClientSession(MongoClientDelegate.java:77)
    at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.getClientSession(MongoClientDelegate.java:185)
    at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.execute(MongoClientDelegate.java:152)
    at com.mongodb.client.internal.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:894)
    at com.mongodb.client.internal.MongoCollectionImpl.executeInsertOne(MongoCollectionImpl.java:443)
    at com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:427)
    at com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:421)
    at com.czb.chargepile.core.MongeTemplate.insert(MongeTemplate.java:59)
    at com.czb.chargepile.manage.X01Manager.insert(X01Manager.java:17)
    at manage.X01ManagerTest.main(X01ManagerTest.java:21)

分析:mongodb数据库连接超时,也就是客户端连不上mongo

代码:

MongoCredential credential = MongoCredential.createCredential(user, databaseName, password);

mongoClient = MongoClients.create(

MongoClientSettings.builder()

.applyToSslSettings(builder -> builder.enabled(true))

.applyToClusterSettings(builder ->

builder.hosts(Arrays.asList(new ServerAddress("localhost", 27017))))

.credential(credential)

.build());

MongoDatabase database = mongoClient.getDatabase(databaseName);

解决:

1、看到错误,首先想到的是用户名密码不对,为了确保密码无误,重新设置了mongo的密码,然而并未好使

2、检查用户所属数据库是否正确,经过检查,发现完全匹配

3、通过:https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-mongodb-java

检查mongo-java-drive版本是否和mongo版本匹配,发现完全匹配

4、最后开始怀疑上面的代码有问题,找官方文档https://mongodb.github.io/mongo-java-driver/3.8/driver/tutorials/authentication/,从这里找到了新的写法,先无脑拷贝,然后运行,发现这里写法是成功的,与自己的代码对比,发现我的代码多了一行

.applyToSslSettings(builder -> builder.enabled(true))

回到我代码,去掉,发现成功了。又回去看官方文档,找到端倪

image

如果使用那个选项,传输过程会使用TLS/SSL对传输层进行加密,但是我的mongo服务是没有对应设置的,所以导致连接不上。

上一篇下一篇

猜你喜欢

热点阅读