本地应用程序通过 ssh 隧道连接 Mongo 不工作

Local application connects Mongo through ssh tunnel is not working

我有一个链接到远程 mongo 服务器的 ssh 隧道。我试图在 Play 服务器中将此本地隧道与 mongo-java-驱动程序一起使用。它抛出超时错误。但是我可以使用 mongo 命令行连接到这个隧道并毫无问题地操作这个数据库。

这是隧道命令:

ssh -f -L 127.0.0.1:27018:$remote_ip:$remote_mongo_port $remote_user\@$remote_host -N

这是我用的mongo.url:

mongodb.default.uri="mongodb://acct:password@127.0.0.1:27018/mydb"

但是,它在尝试连接时抛出此错误。

Caused by: com.mongodb.MongoTimeoutException: Timed out while waiting for a server that matches {serverSelectors=[ReadPreferenceServerSelector{readPreference=primaryPreferred}, LatencyMinimizingServerSelector{acceptableLatencyDifference=15 ms}]} after 9999 ms
    at com.mongodb.BaseCluster.getServer(BaseCluster.java:87)
    at com.mongodb.DBTCPConnector.getServer(DBTCPConnector.java:654)
    at com.mongodb.DBTCPConnector.access0(DBTCPConnector.java:39)
    at com.mongodb.DBTCPConnector$MyPort.getConnection(DBTCPConnector.java:503)
    at com.mongodb.DBTCPConnector$MyPort.get(DBTCPConnector.java:451)
    at com.mongodb.DBTCPConnector.authenticate(DBTCPConnector.java:624)
    at com.mongodb.DBApiLayer.doAuthenticate(DBApiLayer.java:195)
    at com.mongodb.DB.authenticateCommandHelper(DB.java:763)
    at com.mongodb.DB.authenticate(DB.java:719)
    at com.mongodb.casbah.MongoDB.authenticate(MongoDB.scala:86)
    at se.radley.plugin.salat.SalatPlugin$MongoSource$$anonfun$$anonfun$apply.apply(SalatPlugin.scala:33)
    at se.radley.plugin.salat.SalatPlugin$MongoSource$$anonfun$$anonfun$apply.apply(SalatPlugin.scala:32)
    at scala.Option.map(Option.scala:145)
    at se.radley.plugin.salat.SalatPlugin$MongoSource$$anonfun.apply(SalatPlugin.scala:32)
    at se.radley.plugin.salat.SalatPlugin$MongoSource$$anonfun.apply(SalatPlugin.scala:31)
    at scala.Option.flatMap(Option.scala:170)
    at se.radley.plugin.salat.SalatPlugin$MongoSource.connection(SalatPlugin.scala:31)
    at se.radley.plugin.salat.SalatPlugin$$anonfun$onStart.apply(SalatPlugin.scala:136)

尝试使用 -R 而不是 -L,-L 将本地端口转发到远程端口,该端口可以在您连接的服务器上读取。另一方面,-R 将远程端口转发到本地端口,这就是我猜你正在尝试做的事情。

ssh -f -R 127.0.0.1:27018:$remote_ip:$remote_mongo_port $remote_user\@$remote_host -N

试一试

ssh -N -f -L 27017:$remote_address:$remote_mongo_port $ssh_username@$ssh_address