1、增加 Maven 依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
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、原理