关于springboot:SpringBoot-通过-SSH-通道连接远程-MySQL-数据库
1、增加 Maven 依赖<dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.55</version></dependency>2、创立 SSH 连贯工具类import com.jcraft
·
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

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐
所有评论(0)