创建SSH连接和MySQL连接的配置类。 import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
@Configuration
public class MysqlSSHConfig {
@Value("${ssh.host}")
private String sshHost;
@Value("${ssh.port}")
private int sshPort;
@Value("${ssh.user}")
private String sshUser;
@Value("${ssh.password}")
private String sshPassword;
@Value("${mysql.host}")
private String mysqlHost;
@Value("${mysql.port}")
private int mysqlPort;
@Value("${mysql.user}")
private String mysqlUser;
@Value("${mysql.password}")
private String mysqlPassword;
@Value("${mysql.database}")
private String mysqlDatabase;
@Bean
public Session sshSession() throws JSchException {
JSch jsch = new JSch();
Session session = jsch.getSession(sshUser, sshHost, sshPort);
session.setPassword(sshPassword);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
return session;
}
@Bean
public Connection mysqlConnection(Session session) throws SQLException {
int localPort = 3307;
session.setPortForwardingL(localPort, mysqlHost, mysqlPort);
String url = "jdbc:mysql://localhost:" + localPort + "/" + mysqlDatabase + "?useSSL=false";
Connection conn = DriverManager.getConnection(url, mysqlUser, mysqlPassword);
return conn;
}
}