一、实现思路
1 实现思路:本地–>跳板机–>目标数据库
2 IP走向:127.0.0.1:5432 --> 192.168.1.111 -->10.11.12.13:5432
二、引入maven
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
三、创建及关闭ssh通道
package com.yg.housesite.utils.db;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
/** SSH 连贯工具类
* @Author tangqd
* @Date 2022/10/27 16:47
* @Description
*/
public class SshConnection {
//跳板机
String username_ = "用户名";
String password_ = "密码";
String host = "192.168.1.111";
int port = 22;
//本地端口
int local_port = 5432; //本地触发端口,配置文件中数据库端口
String remote_host = "10.11.12.13"; //目标IP
int remote_port = 5432; //目标端口
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();
}
}
四、初始化通道(启动项目)
package com.yg.housesite.utils.db;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.springframework.stereotype.Component;
/**
* @Author tangqd
* @Date 2022/10/27 16:49
* @Description
*/
@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();
}
}
}