1 添加依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
2 配置SSH连接
@Component
@ConditionalOnProperty(prefix = "ssh", value = "enable", havingValue = "true")
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class DataSourceContextListener implements ServletContextListener {
private final SSHConnection connection;
@Override
public void contextInitialized(ServletContextEvent sce) {
connection.init();
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
connection.destroy();
}
}
@Component
@Slf4j
@ConditionalOnProperty(prefix = "ssh", value = "enable", havingValue = "true")
public class SSHConnection {
private Session session;
@Value("${ssh.host}")
private String host;
@Value("${ssh.port}")
private int port;
@Value("${ssh.username}")
private String username;
@Value("${ssh.private.key.path}")
private String privateKeyPath;
@Value("${ssh.remote.server}")
private String remoteServer;
@Value("${ssh.remote.port}")
private int remotePort;
@Value("${ssh.local.port}")
private int localPort;
public void init() {
try {
session = JschUtil.getSession(host, port, username, privateKeyPath, null);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPortForwardingL(localPort, remoteServer, remotePort);
} catch (Exception e) {
log.error("connect error.", e);
}
}
public void destroy() {
this.session.disconnect();
}
}
3 DB配置
######## 数据库名称
afs.database=test
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.url=jdbc:postgresql://localhost:${ssh.local.port}/${afs.database}?sslmode=require&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true
######## username
spring.datasource.username=username
######## password
spring.datasource.password=password
######## 开启SSH
ssh.enable=true
ssh.host=10.10.10.10
ssh.port=22
ssh.username=root
######## 本地public key路径
ssh.private.key.path=/test/custom.pem
######## HOST
ssh.remote.server=192.168.50.17
ssh.remote.port=5432
ssh.local.port=9999