当目标数据库不能直连的,需要一个服务器作为中间跳板的时候,我们需要通过ssh通道连接数据库。

ps:使用ssh连接,相当于本地开了个端口去连接远程的服务,就是ssh通道,本地起的项目监听本地的端口,就可以使用这个通道进行数据传输。

1、引入依赖

<dependency>
            <groupid>com.jcraft</groupid>
            <artifactid>jsch</artifactid>
            <version>0.1.55</version>
 </dependency>

2、代码编写

#ssh连接是否开启
ssh.forward.enabled=true
#ssh连接跳板机地址 必填
ssh.forward.host=
#ssh连接端口  必填  固定
ssh.forward.port=22
#ssh连接用户名  必填  
ssh.forward.username=
#ssh连接密码 
ssh.forward.password=
#本地起的  必填  固定
ssh.forward.from_host=localhost
#本地开启的端口  必填 
ssh.forward.from_port=3307
#需要监听的远程服务的ip  必填
ssh.forward.to_host=
#需要监听的远程端口  必填
ssh.forward.to_port=3306
#ssh连接秘钥地址,也可以使用rsa.ppk文件
ssh.identity=c:\\users\425\\.ssh\\id_rsa

2.1、配置 application.ssh.properties文件

2.2、配置 sshconfiguration代码

import com.jcraft.jsch.jsch;
import com.jcraft.jsch.jschexception;
import com.jcraft.jsch.session;
import lombok.extern.slf4j.slf4j;
import org.springframework.boot.web.servlet.servletcontextinitializer;
import org.springframework.stereotype.component;

import javax.servlet.servletcontext;
import javax.servlet.servletexception;
import java.io.ioexception;
import java.util.properties;

@slf4j
@component
public class sshconfiguration implements servletcontextinitializer {

    public sshconfiguration() {
        try {
            properties p = new properties();
            p.load(getclass().getresourceasstream("/application.ssh.properties"));
            //如果配置文件包含ssh.forward.enabled属性,则使用ssh转发
            if (p.getproperty("ssh.forward.enabled") != null) {
                log.info("ssh forward is opend.");
                log.info("ssh init ……");
                jsch jsch = new jsch();
                //需要使用秘钥时添加
                jsch.addidentity(p.getproperty("ssh.identity"));
                session session = jsch.getsession(p.getproperty("ssh.forward.username"), p.getproperty("ssh.forward.host"), integer.parseint(p.getproperty("ssh.forward.port")));
                session.setconfig("stricthostkeychecking", "no");
                session.setpassword(p.getproperty("ssh.forward.password"));
                session.connect();
                session.setportforwardingl(p.getproperty("ssh.forward.from_host"), integer.parseint(p.getproperty("ssh.forward.from_port")), p.getproperty("ssh.forward.to_host"), integer.parseint(p.getproperty("ssh.forward.to_port")));
            } else {
                log.info("ssh forward is closed.");
            }
        } catch (ioexception e) {
            log.error("ssh ioexception failed.", e);
        } catch (jschexception e) {
            log.error("ssh jschexception failed.", e);
        } catch (exception e) {
            log.error("ssh settings is failed. skip!", e);
        }
    }

    @override
    public void onstartup(servletcontext servletcontext) throws servletexception {
        log.info("已使用ssh连接");
    }
}

2.3、application.yum

spring:
  datasource:
#  localhost:3307 这里是ssh.forward.from_host:ssh.forward.from_port
    url: jdbc:mysql://localhost:3307/mysql?useunicode=true&characterencoding=utf-8&servertimezone=gmt%2b8
#  mysql数据库连接用户名
    username: 
#  mysql数据库连接密码
    password: 
    driver-class-name: com.mysql.cj.jdbc.driver
#   使用了druid去配置及监控连接池和本文无关,可加可不加
    druid:
      initial-size: 2
      min-idle: 1
      max-active: 10
      max-wait: 60000
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      validation-query: select 'x'
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: true

3、启动项目

当看到这里**“已使用ssh连接”**就可以了是连接成功了。

4、出现异常报错

com.jcraft.jsch.jschexception: invalid privatekey: [b@53a7a60c

这是秘钥问题,这个异常只在使用秘钥时候才会有。是秘钥解析失败,并不是使用秘钥连接失败。如果出现这个异常可以到这篇文章中查看:详解java使用jsch与sftp服务器实现ssh免密登录。

这个依赖已经很久没更新了。但是目前本人未发现更好的ssh连接jar包 ↩︎