I can successfully connect to my openshift mysql through workbench, how do I do the same through my spring boot application?
in my 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 openshift you connect to the MySQL Database directly.
Openshift provides you a set of environment variables. See: 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:Where
OPENSHIFT_MYSQL_DB_HOST
is the environment variable name andlocalhost
the default value.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.
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)
If you use Maven add to your pom.xml these elements:
or just download it from 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)
For example:
This class keeps all relevant info for establishing an SSH connection. 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.
3) Define a listener that implements ServletContextListener interface (holding an object of the class defined in step 2)
Notice that we try to create a ssh connection when our app starts, closing it when our app dies.
4) Using Spring, set the DataSource object in your dispatcher-servlet.xml as usual, but pointing to your fowarded port
And that's all. Another possibilty could be creating your own DataSource, extending the one provided by Spring, and adding it the ssh functionality. Maybe the solution detailed here, is better isolated.