Timed out after 30000 ms while waiting to connect

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

报错

 1 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}}]
 2     at com.mongodb.connection.BaseCluster.getDescription(BaseCluster.java:167)
 3     at com.mongodb.client.internal.MongoClientDelegate.getConnectedClusterDescription(MongoClientDelegate.java:106)
 4     at com.mongodb.client.internal.MongoClientDelegate.createClientSession(MongoClientDelegate.java:77)
 5     at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.getClientSession(MongoClientDelegate.java:185)
 6     at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.execute(MongoClientDelegate.java:152)
 7     at com.mongodb.client.internal.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:894)
 8     at com.mongodb.client.internal.MongoCollectionImpl.executeInsertOne(MongoCollectionImpl.java:443)
 9     at com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:427)
10     at com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:421)
11     at com.czb.chargepile.core.MongeTemplate.insert(MongeTemplate.java:59)
12     at com.czb.chargepile.manage.X01Manager.insert(X01Manager.java:17)
13     at manage.X01ManagerTest.main(X01ManagerTest.java:21)

 

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

代码

 1 MongoCredential credential = MongoCredential.createCredential(user, databaseName, password);
 2 
 3 mongoClient = MongoClients.create(
 4 
 5 MongoClientSettings.builder()
 6 
 7 .applyToSslSettings(builder -> builder.enabled(true))
 8 
 9 .applyToClusterSettings(builder ->
10 
11 builder.hosts(Arrays.asList(new ServerAddress("localhost", 27017))))
12 
13 .credential(credential)
14 
15 .build());
16 
17 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/,从这里找到了新的写法,先无脑拷贝,然后运行,发现这里写法是成功的,与自己的代码对比,发现我的代码多了一行

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

 

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


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

posted @ 2019-10-13 19:33  Drebander  阅读(13095)  评论(0编辑  收藏  举报