我有一个远程MySQL数据库服务器,需要与我在本地运行的Spring Boot应用程序连接 .
在Spring Boot Applications加载之前,它首先使用远程服务器进行ssh隧道 .
这是首先创建的主应用程序代码,然后启动ssh tunnel然后启动主应用程序 .
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的嵌入式数据库驱动程序类”
我应该给application.properties中的spring.datasource.url值什么?还是其他任何建议?谢谢 .
1 回答
您正在关闭
finally
块中的SSH隧道 .我建议您也让Spring创建SSH隧道而不是在
main
方法中进行 . 这将允许您为不同的环境选择性地启用/禁用隧道,并且您可以使用属性和其他Spring Boot功能来配置,启动和停止隧道 .像这样的东西会起作用 .
这样您就可以使用Spring来配置和管理隧道 . 如果您愿意,您甚至可以将其作为特定环境的条件 . 在进行本地开发时没有隧道,并将其用于测试和 生产环境 环境 .