LoginSignup
2
3

More than 3 years have passed since last update.

Spring Boot と Cloud Sql を接続

Posted at

どんな記事?

???「時代はもうクラウドなんですよ!!」
僕もそう思うのでクラウドを使ってみようと思います。

Google信者なので GCP を使います。
とりあえずローカル環境からDBに接続してデータのやり取りをします。

使うもの

1.GCP のアカウント(事前に取得しておく)
2.GCP のDBインスタンス(MySQL で作ってます。チュートリアル見ながら事前に作成)
3.Spring Boot
※1 Spring JPA を依存に含めています。それ以外は他のSpringInitializer記事を参考に。
※2 個人的な趣味でMavenを使います。

目標

クラウド上のDBと接続して、データのやりとりができるようになる。

ステップ1:アプリを作る

データのやり取りをするだけでよいので、api として実装します。

DataGetController.java
@RestController
public class DataGetController {

    @Autowired
    TestDataService testDataService;

    @RequestMapping(value = "/api/data/get", method = RequestMethod.GET)
    public List<TestData> doGet() throws Exception {
        return testDataService.getTestDataAll();
    }
}
TestDataService.java
@Service
public class TestDataService {

    @Autowired
    TestDataRepository testDataRepository;

    public List<TestData> getTestDataAll() {
        return testDataRepository.findAll();
    }

    @Transactional
    public boolean insertTestData(final TestData testData) {
        testDataRepository.save(testData);
        return true;
    }
}
TestData.java
@Entity
@Table(name = "test_data")
public class TestData{

    @Id
    @GeneratedValue
    private Integer id;

    @Column(name = "name", nullable = false)
    private String name;

    private int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

※Repositoryは割愛します。JPA の記事を見てみてください。

ステップ2:設定する

公式を参考にしながら設定を書いていきます。
App Engine から Cloud Sql への接続

公式ではjavaなどのソース上で書いていますが、Spring Boot でやる場合は起動時に設定ファイルで読み込ませてあげないと勝手に違うものを見に行こうとして落ちます。(1敗
なので設定ファイルで読み込ませてあげる必要があるんですね。

application.yml
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://XXX.XXX.XXX.XXX/test_database
    username: root
    password: root
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      data-source-properties:
        socketFactory: com.google.cloud.sql.mysql.SocketFactory
        cloudSqlInstance: XXXX:asia-northeast1:XXXX

そのままymlに書き換えただけです。

ステップ3:依存関係の追加

このまま起動すると落ちます。
見慣れない例外がだらだら出てきます。
これを書いている今は解決済みで、例外名なんかは忘れてしまいましたが……

調べてみると色々とやることがあるみたいですが、まずは依存関係の追加です。

Cloud Sql に接続するには以下を追加します。

pom.xml
<!-- project配下 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-gcp-dependencies</artifactId>
                <version>1.2.3.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.google.cloud</groupId>
                <artifactId>libraries-bom</artifactId>
                <version>11.0.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    ~~~   

<!-- dependencies配下 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-gcp-starter-sql-mysql</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.cloud</groupId>
            <artifactId>google-cloud-storage</artifactId>
        </dependency>

これでOKです。

ステップ4:設定の追加

まだ落ちます。
Cloud Sql と接続するのに必要な設定を yml に追加します。

application.yml
#以下を追加
  cloud:
    gcp:
      sql:
        database-name: test_database
        instance-connection-name: XXXX:asia-northeast1:XXXX

これさっき書いてなかった? って思った方もいらっしゃるかと思いますが、さっきも書きました。
ですが、プロパティ名が違いますね。
さっきのはHikariCP というライブラリでコネクションプールを作るためのものでした。
今度はCloud Sql と接続するための設定です。

ステップ5:実行

多分ここまでで動くと思います。

localhost:8080/api/data/get

[{"name":"name1"}]

事前に入れておいたデータが返ってきました。

まとめ

これでクラウドエンジニアの仲間入りです!!
仲間に入れてください!

読んでいただき、ありがとうございました。
間違いやご指摘あれば、コメントにお願いしますmm

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