Timed out after 30000 ms while waiting to connect
阿新 • • 發佈:2019-10-13
今天使用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服務是沒有對應設定的,所以導致連線不