Java Spring boot 使用SSH连接Mysql

  1. 导入JSch和MySQL驱动程序的依赖。
    <dependency>
        <groupId>com.jcraft</groupId>
        <artifactId>jsch</artifactId>
        <version>0.1.55</version>
    </dependency>
    
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>{your version}</version>
    </dependency>

  2. 创建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;
        }
    }