今天首次碰到在SpringBoot中使用阿里云rds数据库,搜索一了一番资料,最后成功实现。然后在这里做下自我总结。(个人用到是SSH方式进行连接)
1、在pom文件中添加jar包依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>
2、编写Listener
我这里使用注解方式,进行实现,SSH连接使用密钥方式
监听器类代码
@WebListener
public class MyContextListener implements ServletContextListener {
private static final Logger LOGGER = LoggerFactory.getLogger(MyContextListener.class);
private SSHConnection conexionssh;
public MyContextListener() {
super();
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
LOGGER.info("初始化开始。。。。");
try {
conexionssh = new SSHConnection();
} catch (Throwable e) {
// error connecting SSH server
LOGGER.error("error",e)
}
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
LOGGER.info("关闭连接!");
// disconnect
conexionssh.closeSSH();
}
}
SSHConnection代码
/** 秘钥文件地址*/
private final static String S_PATH_FILE_PRIVATE_KEY = "E:\\privateKey\\zr-jenkins.pem";
/** konwn_hosts 文件*/
private final static String S_PATH_FILE_KNOWN_HOSTS = "C:\\Users\\xuby\\.ssh\\known_hosts";
// private final static String S_PASS_PHRASE = "D10mCUHIjQALb4sP";
//选择本地一个未占用的端口(个人理解,这端口对应后面数据库连接的端口)
private final static int LOCAl_PORT = 3307;
//远程数据库端口
private final static int REMOTE_PORT = "";
//ssh端口
private final static int SSH_REMOTE_PORT ="" ;
//ssh 登录用户名
private final static String SSH_USER = "";
//远程ssh ip地址
private final static String SSH_REMOTE_SERVER = "";
//远程数据库地址
private final static String MYSQL_REMOTE_SERVER = "";
private Session sesion;
public void closeSSH (){
sesion.disconnect();
}
public SSHConnection () throws Throwable{
JSch jsch = new JSch();
jsch.setKnownHosts(S_PATH_FILE_KNOWN_HOSTS);
// jsch.addIdentity(S_PATH_FILE_PRIVATE_KEY, S_PASS_PHRASE.getBytes());
jsch.addIdentity(S_PATH_FILE_PRIVATE_KEY);
sesion = jsch.getSession(SSH_USER, SSH_REMOTE_SERVER, SSH_REMOTE_PORT);
//跳过检查
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
sesion.setConfig(config);
sesion.connect();
sesion.setPortForwardingL(LOCAl_PORT, MYSQL_REMOTE_SERVER, REMOTE_PORT);
}
3、配置监听器
在pom文件中增加配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
入口启动类中增加注解@ServletComponentScan
4、yml文件中配置数据库连接
注意这里的端口号是前面的LOCAl_PORT一致,地址为:127.0.0.1
到这里已经完成所有的配置。(新手第一次写博客,请各位多多指教)。