我有一个远程MySQL数据库服务器,需要连接到运行在本地的Spring应用程序。
在Spring应用程序加载之前,它从使用远程服务器的ssh隧道开始。
这里是主要的应用程序代码,它首先创建和ssh隧道,然后启动主应用程序。
public class XXXCoreApplication {
public static void main(String[] args) throws SQLException {
Connection connection = null;
Session session = null;
String host = "XX.XXX.XX.XXX";
String servUser = "user";
String servPwd = "pass";
int port = 22;
String rhost = "localhost";
int rport = 3306;
int lport = 3307;
String driverName = "com.mysql.jdbc.Driver";
String db2Url = "jdbc:mysql://localhost:" + lport + "/xxx_core";
String dbUsr = "MT";
String dbPwd = "****";
try {
JSch jsch = new JSch();
// Get SSH session
session = jsch.getSession(servUser, host, port);
session.setPassword(servPwd);
java.util.Properties config = new java.util.Properties();
// Never automatically add new host keys to the host file
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
// Connect to remote server
session.connect();
// Apply the port forwarding
session.setPortForwardingL(lport, rhost, rport);
// Connect to remote database
Class.forName(driverName);
connection = DriverManager.getConnection(db2Url, dbUsr, dbPwd);
System.out.println("Connection to database established!");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null && !connection.isClosed()) {
connection.close();
}
if (session != null && session.isConnected()) {
session.disconnect();
}
}
SpringApplication.run(XXXCoreApplication.class, args);
}
}
但是我的application.properties文件是空的,可能是故障点。
它给出了使用空application.properties的错误:
“无法确定数据库类型NONE的嵌入式数据库驱动程序类”
我应该在spring.datasource.url中给出application.properties值什么?或者其他建议?谢谢。
发布于 2018-01-23 05:54:00
您正在关闭finally
块中的SSH隧道。
我建议您也让Spring创建SSH隧道,而不是在main
方法中这样做。这将允许您为不同的环境选择性地启用/禁用隧道,并且可以使用属性和其他Spring特性来配置、启动和停止隧道。
像这样的东西会管用的。
public class SshTunnelStarter {
@Value("${ssh.tunnel.url}")
private String url;
@Value("${ssh.tunnel.username}")
private String username;
@Value("${ssh.tunnel.password}")
private String password;
@Value("${ssh.tunnel.port:22}")
private int port;
private Session session;
@PostConstruct
public void init() throws Exception {
JSch jsch = new JSch();
// Get SSH session
session = jsch.getSession(servUser, host, port);
session.setPassword(servPwd);
java.util.Properties config = new java.util.Properties();
// Never automatically add new host keys to the host file
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
// Connect to remote server
session.connect();
// Apply the port forwarding
session.setPortForwardingL(lport, rhost, rport);
}
@PreDestroy
public void shutdown() throws Exception {
if (session != null && session.isConnected()) {
session.disconnect();
}
}
}
通过这种方式,您可以使用Spring来配置和管理隧道。如果您愿意,甚至可以在特定的环境中设置它的条件。在进行本地开发时,不设隧道,并使其能用于测试和生产环境。
https://stackoverflow.com/questions/48397716
复制