LoginSignup
8
13

More than 5 years have passed since last update.

JDBCでSSHトンネルを経由してMySQLに接続する方法

Posted at

vagrant等で起動した仮想マシン上のMySQLにローカルマシンからSSHトンネルを利用してJDBCで接続する方法を調べたのでメモ

参考にしたサイト

環境

  • Java 8
  • SpringBoot
  • Gradle
  • vagrant
    • CentOS7
    • MySQL 5.6.25

vagrantのポートフォワード設定

下記の設定を追記する

config.vm.network "forwarded_port", guest: 3306, host: 3306

必要なライブラリの設定

jschをライブラリの依存関係に含める。

build.gradle(抜粋)
dependencies {
    compile 'org.springframework.boot:spring-boot-starter'
    compile 'org.springframework.boot:spring-boot-starter-jdbc'
    compile 'mysql:mysql-connector-java:5.1.35'
    compile 'com.jcraft:jsch:0.1.53'
}

DB接続設定

application.properties
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/${DB名}
spring.datasource.username=${ユーザ名}
spring.datasource.password=${パスワード}
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

MySQLのデータ

test_table

id value
1 hoge
2 fuga
3 piyo

実装

JSchを利用してSSH接続し、ポートフォワードする。
vagrant側でポートフォワードしている為、不要かと思ったがコメントアウトした状態では接続できなかった。

Main.java
@SpringBootApplication
public class Main {

    public static void main(String[] args) {
        try (ConfigurableApplicationContext ctx = SpringApplication.run(Main.class, args)) {
            Main m = ctx.getBean(Main.class);
            m.method();
        }
    }

    @Autowired
    private JdbcTemplate jdbc;

    public void method() {

        Session session = null;

        try {
            String strSshUser = "vagrant";
            String strSshPassword = "vagrant";
            String strSshHost = "127.0.0.1";
            int nSshPort = 2222;

            String strRemoteHost = "127.0.0.1";
            int nLocalPort = 3306;
            int nRemotePort = 3306;


            final JSch jsch = new JSch();
            session = jsch.getSession(strSshUser, strSshHost, nSshPort);
            session.setPassword(strSshPassword);

            final Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);

            session.connect();
            session.setPortForwardingL(nLocalPort, strRemoteHost, nRemotePort);

            List<Map<String, Object>> list = this.jdbc.queryForList("SELECT * FROM test_table");
            list.forEach(System.out::println);

        } catch (JSchException e) {
            e.printStackTrace();
        } finally {
            session.disconnect();
        }
    }
}
{id=1, value=hoge}
{id=2, value=fuga}
{id=3, value=piyo}
8
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
13