Java通过SSH转发连接MySQL

1.添加依赖

<dependency>
  <groupId>com.jcraft</groupId>
  <artifactId>jsch</artifactId>
  <version>0.1.55</version>
</dependency>

2.创建MySQLSSHConnection类

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

import java.util.Properties;

public class MySQLSSHConnection {
      //本地SSH地址
    private final static String S_PATH_FILE_KNOWN_HOSTS = "localhost";
    private final static int LOCAl_PORT = 3307;
  
      //SSH登录信息
    private final static int SSH_REMOTE_PORT = 22;
    private final static String SSH_USER = "user";
    private final static String SSH_PASSWORD = "password";
    private final static String SSH_REMOTE_SERVER = "112.74.39.111";
  
      //远程MySQL服务地址
    private final static String MYSQL_REMOTE_SERVER = "xxx.mysql.rds.aliyuncs.com";
      //远程MySQL端口
    private final static int REMOTE_PORT = 3306;

    private Session sesion; 

    public void closeSSH() {
        sesion.disconnect();
    }

    public MySQLSSHConnection() throws Throwable {
        JSch jsch = new JSch();
        jsch.setKnownHosts(S_PATH_FILE_KNOWN_HOSTS);
        sesion = jsch.getSession(SSH_USER, SSH_REMOTE_SERVER, SSH_REMOTE_PORT);
        sesion.setPassword(SSH_PASSWORD);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        sesion.setConfig(config);
        sesion.connect();
        sesion.setPortForwardingL(LOCAl_PORT, MYSQL_REMOTE_SERVER, REMOTE_PORT);
    }
}

3.创建MyContextListener类

import org.springframework.stereotype.Component;

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

@WebListener
@Component
public class MyContextListener implements ServletContextListener {

    private MySQLSSHConnection connection;

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        try {
            connection = new MySQLSSHConnection();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        connection.closeSSH();
    }
}

4.修改配置

spring:
  shardingsphere:
    datasource:
      ds0:
        jdbc-url: jdbc:mysql://localhost:3307/fingerprint?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false&autoReconnect=true&failOverReadOnly=false
        username: mysql_user
        password: mysql_password
如果觉得我的文章对你有用,请随意赞赏