我需要通过ssh连接连接到Mysql RDS DB,我试过的是打开一个ssh隧道,然后连接到该数据库,但它没有用 .
以下是我的代码:
int lport = 3306;
String host = "10.254.64.135";
String rhost = "localhost";
int rport = 8000;
String user = "ubuntu";
String dbuserName = "someusername";
String dbpassword = "somepassword";
String dburl = "jdbc:mysql://somedbhost.us-east-1.rds.amazonaws.com:3306";
String driverName = "com.mysql.jdbc.Driver";
String driverName2 = "org.gjt.mm.mysql.Driver";
Session session = null;
try {
final java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
final JSch jsch = new JSch();
session = jsch.getSession(user, host, 22);
jsch.addIdentity("C:\\Users\\rop\\workspace\\awskey.pem");
session.setConfig(config);
session.connect();
System.out.println("Connected through SSH");
final int assinged_port = session.setPortForwardingL(rport, host,lport );
System.out.println("localhost:" + assinged_port + " -> " + rhost + ":" + rport);
System.out.println("Port Forwarded");
//mysql database connectivity
Class.forName("com.mysql.jdbc.Driver").newInstance();
//String url = "jdbc:mysql://localhost:" + rport + "/" + db;
con = DriverManager.getConnection(dburl, dbuserName, dbpassword);
System.out.println("Mysql Database connection established");
System.out.println("DONE");
上面的代码崩溃,出现以下异常,并在此行中崩溃“con = DriverManager.getConnection(dburl,dbuserName,dbpassword);”:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:通信链路故障成功发送到服务器的最后一个数据包是0毫秒前 . 驱动程序未收到来自服务器的任何数据包 .
这意味着当我们从mysql工作台连接时,它确实正常连接,在快照下面:
请注意,ssh主机ip与db主机ip不同
谢谢 .