To connect to MongoDB from Java I use:
MongoClient mongoClient = new MongoClient("localhost", port);
And it works fine. Now I would like to connect to MongoDB which is on machine where I have to login by SSH. I try to use JSch for this, here is my code:
String host = "host";
String user = "user";
String password = "pass";
int port = 22;
int tunnelLocalPort = 3309;
String tunnelRemoteHost = "host";
int tunnelRemotePort = 3306;
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
localUserInfo lui = new localUserInfo();
session.setUserInfo(lui);
session.connect();
session.setPortForwardingL(tunnelLocalPort, tunnelRemoteHost, tunnelRemotePort);
Everything looks fine, I can connect, but here is a problem:
MongoClient mongoClient = new MongoClient("localhost", 27020);
List<String> databaseNames = mongoClient.getDatabaseNames();
LOG.info("DB names=" + databaseNames);
And error is:
Aug 21, 2014 4:12:29 PM com.mongodb.DBTCPConnector initDirectConnection
Warnung: Exception executing isMaster command on localhost/127.0.0.1:27020
java.io.IOException: couldn't connect to [localhost/127.0.0.1:27020] bc:java.net.ConnectException: Connection refused: connect
at com.mongodb.DBPort._open(DBPort.java:214)
Should I set something more to connect? How can I check from Java that program connects, when I check session.isConnected()
output is true
. When I use PuTTY everything works fine.