使用SSH连接数据库示例代码记录

需求:

数据库使用普通连接失败,需要使用ssh连接方式。

原本配置:

1
2
3
4
5
oil-pay:
url: jdbc:mysql://ip:3306/数据库名?Unicode=true&characterEncoding=UTF-8
username: 用户名
password: 密码
driver-class-name: com.mysql.cj.jdbc.Driver

使用ssh需要修改配置及增加代码:

ssh配置:

1
2
3
4
5
oil-pay:
url: jdbc:mysql://127.0.0.1:3307/数据库名?Unicode=true&characterEncoding=UTF-8&useSSL=false
username: 用户名同上
password: 密码同上
driver-class-name: com.mysql.cj.jdbc.Driver

增加config代码:

  1. 编写MyContextListener实现ServletContextListener
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
@WebListener
@Component
@Slf4j
public class MyContextListener implements ServletContextListener {
private SSHConnection conexionssh;
public MyContextListener() {
super();
}
/**
* @see ServletContextListener#contextInitialized(ServletContextEvent)
*/
@Override
public void contextInitialized(ServletContextEvent arg0) {
// 建立连接
log.info("准备建立连接");
try {
conexionssh = new SSHConnection();
conexionssh.SSHConnection();
log.info("成功建立SSH连接");
} catch (Throwable e) {
log.error("创建SSH连接失败");
// error connecting SSH server
e.printStackTrace();
}
}
/**
* @see ServletContextListener#contextDestroyed(ServletContextEvent)
*/
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// 断开连接
log.info("准备关闭SSH连接");
try {
conexionssh.closeSSH();
log.info("成功断开SSH连接");
} catch (Exception e) {
log.error("断开SSH连接出错");
// error closing SSH server
e.printStackTrace();
}
}
}
  1. 编写SSHConnection
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public class SSHConnection {
/**
* SSH服务器登录名
*/
private String user = "root";
/**
* SSH服务器登录密码
*/
private String password = "xxxxxx";
/**
* SSH服务器公网IP
*/
private String host = "x.x.x.x";
/**
* SSH服务器默认端口
*/
private int port = 22;
/**
* 本地端口,随便选一个没占用的即可
*/
private int local_port = 3307;
/**
* 需要访问的mysql的IP
*/
private String remote_host = "ip";
/**
* 需要访问的mysql的端口号
*/
private int remote_port = 3306;

private Session session = null;
/**
* 建立SSH连接
*/
public void SSHConnection() {
try {
JSch jsch = new JSch();
session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
// 日志打印
session.connect();
session.setPortForwardingL(local_port, remote_host, remote_port);
} catch (Exception e) {
log.error("建立SSH连接失败");
}
}
/**
* 断开SSH连接
*/
public void closeSSH () {
this.session.disconnect();
}
}