SpringBoot 通过 SSH 通道连接远程 MySQL 数据库

1、添加 Maven 依赖


    com.jcraft
    jsch
    0.1.55

2、创建 SSH 连接工具类

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SshConnection {

    //跳板机
    String username = "username";
    String password = "password";
    String host = "host";
    int port = 22;

    //本地端口
    int local_port = 3307;
    String remote_host = "192.168.5.56";
    int remote_port = 3306;
    Session session;

    /**
     * 建立SSH连接
     */
    public void init() {
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(username, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            session.setPortForwardingL(local_port, remote_host, remote_port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 断开SSH连接
     */
    public void destroy() {
        this.session.disconnect();
    }
}

3、管理 SSH 连接

import org.springframework.stereotype.Component;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
@Component
public class SshContextListener implements ServletContextListener {
    private SshConnection sshConnection;

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("==========>Context initialized...");
        try {
            sshConnection = new SshConnection();
            sshConnection.init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("==========>Context destroyed...");
        try {
            sshConnection.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4、配置 application.properties

spring.datasource.url=jdbc:mysql://127.0.0.1:3307/test?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

注意:

数据库连接地址由 192.168.5.56:3306 改为 127.0.0.1:3307 ,SSH 连接会把 127.0.0.1:3307 上的操作转发到 192.168.5.56:3306

5、原理

你可能感兴趣的:(springboot)