我可以通过工作台成功地连接到我的openshift mysql,我如何通过我的spring boot应用程序实现同样的连接?
在我的application.properties中:
# Connection url for the database
spring.datasource.url = jdbc:mysql://<SSH_username>:<SSH_password>@<mysql_hostname>:<mysql_port>/<mysql_schema>
# Username and password
spring.datasource.username = <mysql_username>
spring.datasource.password = <mysql_password>
我在哪里提供私钥?
像往常一样,幸运的是,有几种方法可以做到这一点,但我会试着解释最简单的一种对我有效的方法。
1)将Jcraft库添加到类路径(用于处理SSH连接)
如果使用Maven,请将以下元素添加到pom.xml中:
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>
或者从http://www.jcraft.com/jsch/下载
2)创建一个连接到SSH服务器的类(这里,我们使用上一步中导入的库)
例如:
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class SSHConnection {
private final static String S_PATH_FILE_PRIVATE_KEY = "C:\\Users\\Val\\.ssh\\privatekeyputy.ppk"; \\windows absolut path of our ssh private key locally saved
private final static String S_PATH_FILE_KNOWN_HOSTS = "C:\\Users\\Val\\.ssh\\known_hosts";
private final static String S_PASS_PHRASE = "mypassphrase";
private final static int LOCAl_PORT = 3307;
private final static int REMOTE_PORT = 3306;
private final static int SSH_REMOTE_PORT = 22;
private final static String SSH_USER = "87a34c7f89f5cf407100093c";
private final static String SSH_REMOTE_SERVER = "myapp-mydomain.rhcloud.com";
private final static String MYSQL_REMOTE_SERVER = "127.6.159.102";
private Session sesion; //represents each ssh session
public void closeSSH ()
{
sesion.disconnect();
}
public SSHConnection () throws Throwable
{
JSch jsch = null;
jsch = new JSch();
jsch.setKnownHosts(S_PATH_FILE_KNOWN_HOSTS);
jsch.addIdentity(S_PATH_FILE_PRIVATE_KEY, S_PASS_PHRASE.getBytes());
sesion = jsch.getSession(SSH_USER, SSH_REMOTE_SERVER, SSH_REMOTE_PORT);
sesion.connect(); //ssh connection established!
//by security policy, you must connect through a fowarded port
sesion.setPortForwardingL(LOCAl_PORT, MYSQL_REMOTE_SERVER, REMOTE_PORT);
}
}
@WebListener
public class MyContextListener implements ServletContextListener {
private SSHConnection conexionssh;
public MyContextListener()
{
super();
}
/**
* @see ServletContextListener#contextInitialized(ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent arg0)
{
System.out.println("Context initialized ... !");
try
{
conexionssh = new SSHConnection();
}
catch (Throwable e)
{
e.printStackTrace(); // error connecting SSH server
}
}
/**
* @see ServletContextListener#contextDestroyed(ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent arg0)
{
System.out.println("Context destroyed ... !");
conexionssh.closeSSH(); // disconnect
}
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3307/yourSchema" />
<property name="username" value="admin4ajCbcWM" />
<property name="password" value="dxvfwEfbyaPL-z" />
</bean>