需要依赖的jar包
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
</dependency>
开启SSH通道代码
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.util.Properties;
/**
* @author deh
*/
public class SshConnection {
/**
* 本地映射端口号
*/
private final static int LOCAl_PORT = 13306;
/**
* SSH通道IP地址
*/
private final static String SSH_REMOTE_SERVER = "119.29.888.114";
/**
* SSH通道用户
*/
private final static String SSH_USER = "dbbr";
/**
* SSH通道用户密码
*/
private final static String SSH_PASSWORD = "dbbr";
/**
* 数据库IP
*/
private final static String MYSQL_REMOTE_SERVER = "xxxxx.aliyuncs.com";
/**
* 数据库端口
*/
private final static int REMOTE_PORT = 3306;
public SshConnection() throws Throwable {
JSch jsch = new JSch();
/*获取SSH通道*/
Session sesion = jsch.getSession(SSH_USER, SSH_REMOTE_SERVER);
sesion.setPassword(SSH_PASSWORD);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
sesion.setConfig(config);
/*SSH通道连接*/
sesion.connect();
/*SSH通道映射*/
sesion.setPortForwardingL(LOCAl_PORT, MYSQL_REMOTE_SERVER, REMOTE_PORT);
}
public static void main(String[] args) {
try {
new SshConnection();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
启动上面的主方法开启ssh通道连接,mybatis配置文件中数据库配置更改为
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:13306/con?useUnicode=true&zeroDateTimeBehavior=convertToNull&characterEncoding=utf8" userId="root" password="xxxxxx">
</jdbcConnection>
启动配置文件,则可以正常连接到数据库了