简体   繁体   English

Spring Boot SSH Mysql?

[英]Spring Boot SSH Mysql?

I can successfully connect to my openshift mysql through workbench, how do I do the same through my spring boot application? 我可以通过工作台成功连接到我的openshift mysql,如何通过我的spring启动应用程序执行相同操作?

in my application.properties: 在我的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>

where do I supply my private key? 我在哪里提供私钥?

In order to get access from your local app to your Mysql server via SSH (such as using MySql-Openshift), the "only" extra thing you would need to do, is establish a previous SSH connection, before your DataSource object tries to get a connection. 为了通过SSH从本地应用程序访问您的Mysql服务器(例如使用MySql-Openshift),您需要做的“唯一”额外事情是在DataSource对象尝试获取之前建立先前的SSH连接一个连接。

As usual, and luckily, there are several ways to do that, but I would try to explain the simplest one that has worked for me. 像往常一样,幸运的是,有几种方法可以做到这一点,但我会尝试解释对我有用的最简单的方法。

1) Add Jcraft Library to your classpath (Used to work with SSH connections) 1) 将Jcraft库添加到类路径 (用于处理SSH连接)

If you use Maven add to your pom.xml these elements: 如果您使用Maven添加到您的pom.xml这些元素:

   <dependency>
        <groupId>com.jcraft</groupId>
        <artifactId>jsch</artifactId>
        <version>0.1.53</version>
    </dependency>

or just download it from http://www.jcraft.com/jsch/ 或者只是从http://www.jcraft.com/jsch/下载

2) Create a class to connect to your SSH server (Here, we use the library imported in the previous step) 2) 创建一个连接SSH服务器的类 (这里,我们使用上一步导入的库)

For example: 例如:

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); 

}
}

This class keeps all relevant info for establishing an SSH connection. 此类保留用于建立SSH连接的所有相关信息。 Notice that we only have defined two methods: the constructor, for instantiate the ssh connection, represented by the only non-static field of the class, and other, to get disconnected/close the ssh connection. 请注意,我们只定义了两个方法:构造函数,用于实例化ssh连接,由类的唯一非静态字段表示,以及其他方法,以断开连接/关闭ssh连接。

3) Define a listener that implements ServletContextListener interface (holding an object of the class defined in step 2) 3) 定义一个实现ServletContextListener接口的监听器 (保存在步骤2中定义的类的对象)

Notice that we try to create a ssh connection when our app starts, closing it when our app dies. 请注意,我们尝试在应用启动时创建ssh连接,在应用程序死亡时关闭它。

@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
}

4) Using Spring, set the DataSource object in your dispatcher-servlet.xml as usual, but pointing to your fowarded port 4)使用Spring,像往常一样在dispatcher-servlet.xml中设置DataSource对象, 但是指向你的fowarded端口

<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>

And that's all. 就这样。 Another possibilty could be creating your own DataSource, extending the one provided by Spring, and adding it the ssh functionality. 另一种可能性是创建自己的DataSource,扩展Spring提供的数据源,并添加ssh功能。 Maybe the solution detailed here, is better isolated. 也许这里详述的解决方案更好地隔离。

In openshift you connect to the MySQL Database directly. 在openshift中,您可以直接连接到MySQL数据库。

Openshift provides you a set of environment variables. Openshift为您提供了一组环境变量。 See: https://developers.openshift.com/en/managing-environment-variables.html#database-variables 请参阅: https//developers.openshift.com/en/managing-environment-variables.html#database-variables

You need to use those to connect 您需要使用它们进行连接

inside your application.properties you can use environment variables like this: 在您的application.properties您可以使用如下环境变量:

spring.xxx=${OPENSHIFT_MYSQL_DB_HOST:localhost}

Where OPENSHIFT_MYSQL_DB_HOST is the environment variable name and localhost the default value. 其中OPENSHIFT_MYSQL_DB_HOST是环境变量名称, localhost是默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM