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服務是沒有對應設置的,所以導致連接不上。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM