DataSource 的 getConnection() 忽略端口
DataSource's getConnection() ignores port
我尝试通过 ssh 隧道创建到远程服务器的连接。在我的尝试中,我同时使用了 jsch 和 putty。
int sshPort = 22;
Connection conn = null;
Session session = null;
try {
//Set StrictHostKeyChecking property to no to avoid UnknownHostKey issue
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
session = jsch.getSession("sshUser", "sshHost", sshPort);
session.setPassword(sshPassword);
session.setConfig(config);
session.connect();
session.setPortForwardingL(8806, "127.0.0.1", 3306);
BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
//I can type here any value of port, does not matter connection will be created on port 3306
basicDataSource.setUrl("jdbc:mysql://localhost:8806/db");
basicDataSource.setUsername("user");
basicDataSource.setPassword("password");
}
根据这段代码,我预计一些 sshHost:22
将在 localhost:8806
中可用。
但我得到的不是这个 connection = dataSource.getConnection();
,它始终连接到 localhost:3306
上的数据库。
正如我之前所说,我也尝试通过 Putty 连接 - 结果相同,通过代码连接忽略端口。
P.S。 Putty 的隧道只有当我在 IDEA 的数据库工具中连接到 'localhost:8806' 时才有效。
P.P.S。感谢 @Cool 的建议,现在我可以从代码中创建隧道了。但是 dataSource 继续忽略该端口。
您应该将“8806”转发到“3306”而不是“22”端口。
所以我现在无法测试它,但你应该使用以下行
session.setPortForwardingL(8806, "sshHost", 3306);
顺便说一句,您可以使用下面的内容,而无需腻子等。
ssh sshUser@sshHost -L 8806:localhost:3306
我尝试通过 ssh 隧道创建到远程服务器的连接。在我的尝试中,我同时使用了 jsch 和 putty。
int sshPort = 22;
Connection conn = null;
Session session = null;
try {
//Set StrictHostKeyChecking property to no to avoid UnknownHostKey issue
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
session = jsch.getSession("sshUser", "sshHost", sshPort);
session.setPassword(sshPassword);
session.setConfig(config);
session.connect();
session.setPortForwardingL(8806, "127.0.0.1", 3306);
BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
//I can type here any value of port, does not matter connection will be created on port 3306
basicDataSource.setUrl("jdbc:mysql://localhost:8806/db");
basicDataSource.setUsername("user");
basicDataSource.setPassword("password");
}
根据这段代码,我预计一些 sshHost:22
将在 localhost:8806
中可用。
但我得到的不是这个 connection = dataSource.getConnection();
,它始终连接到 localhost:3306
上的数据库。
正如我之前所说,我也尝试通过 Putty 连接 - 结果相同,通过代码连接忽略端口。
P.S。 Putty 的隧道只有当我在 IDEA 的数据库工具中连接到 'localhost:8806' 时才有效。
P.P.S。感谢 @Cool 的建议,现在我可以从代码中创建隧道了。但是 dataSource 继续忽略该端口。
您应该将“8806”转发到“3306”而不是“22”端口。 所以我现在无法测试它,但你应该使用以下行
session.setPortForwardingL(8806, "sshHost", 3306);
顺便说一句,您可以使用下面的内容,而无需腻子等。
ssh sshUser@sshHost -L 8806:localhost:3306