简体   繁体   中英

How to connect to MongoDB on EC2 using Java driver

I followed tutorial http://www.jcraft.com/jsch/examples/PortForwardingL.java.html and http://www.jcraft.com/jsch/examples/UserAuthPubKey.java.html and I know how to connect to EC2 Ubuntu instance via SSH using pem file as a key. I can interact with EC2 instance in IntelliJ console as well as in putty. But I want to connect to MongoDB and use command described here . I tried to use new MongoClient with localhost and ec2 address with port 22 and 27017, but every combination failed.

This is output from console:

INFO: Cluster created with settings {hosts=[ec2Instance:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
com.mongodb.diagnostics.logging.JULLogger log
INFO: Exception in monitor thread while connecting to server ec2Instance:27017
com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.connection.SocketStream.open(SocketStream.java:63)
    at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:114)
    at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
    at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
    ... 3 more

And this is my code:

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
import com.mongodb.MongoClient;


public class Connection {

    private String pathToKey = "path to pem file";
    private String user = "ubuntu";
    private String hostname;

    private int tunnelLocalPort = 22;
    private int tunnelRemotePort = 27017;


    public Connection(String hostname) {
        this.hostname = hostname;
        createConnection();
    }


    private void createConnection() {
        JSch JavaSecureChannel = new JSch();

        try {
            Session session = JavaSecureChannel.getSession(user, hostname, tunnelLocalPort);
            UserInfo userInfo = new OwnUserInfo();

            JavaSecureChannel.addIdentity(pathToKey);
            session.setUserInfo(userInfo);

            session.connect();
            session.setPortForwardingL(tunnelLocalPort, "host", tunnelRemotePort);

            MongoClient client = new MongoClient("ec2Instance");  

            com.jcraft.jsch.Channel channel = session.openChannel("shell");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            channel.connect();
            // these four lines connect to terminal and I can write commands into IntelliJ console

        } catch (JSchException e) {
            e.printStackTrace();
        }
    }
}

Can someone help me?

You can set up SSH tunneling on your local computer to connect through port 22 like any SSH-enabled client eg Robomongo or IntelliJ do. But it is a hassle.

Unless your network security specifically prohibits opening port 27017 or whatever you are running Mongo on, just open it in EC2 (Security Groups). All basic database security precautions apply ie you should be connecting as a limited-permission application-, not "root"-level user, and of course Mongo should be started with auth=true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM