Cloud Datastore を使用した Spring Boot アプリケーション

Google Cloud Datastore は、自動スケーリングと高パフォーマンスを実現し、アプリケーション開発を簡素化するように構築された NoSQL ドキュメント データベースです。

ラボの内容

  • Cloud Datastore を使用して Spring Boot で Java オブジェクトを保存および取得する方法

必要なもの

  • Google Cloud Platform プロジェクト
  • ChromeFirefox などのブラウザ

このチュートリアルの利用方法をお選びください。

通読するのみ 通読し、演習を行う

Google Cloud Platform サービスのご利用経験についてどのように評価されますか?

初心者 中級者 上級者

セルフペース型の環境設定

Google アカウント(Gmail または Google Apps)をまだお持ちでない場合は、アカウントを作成する必要があります。Google Cloud Platform Console(console.cloud.google.com)にログインして、新しいプロジェクトを作成します。

2016-02-10 12:45:26.png のスクリーンショット

プロジェクト ID を忘れないようにしてください。プロジェクト ID はすべての Google Cloud プロジェクトを通じて一意の名前にする必要があります(上記の名前はすでに使用されているので使用できません)。以降、このコードラボでは PROJECT_ID と呼びます。

次に、Google Cloud リソースを使用するために、Cloud Console で課金を有効にする必要があります。

この Codelab を実施した場合、費用は数ドルを超えることはありませんが、より多くのリソースを使用する場合や、実行したままにしておくとさらにコストがかかる場合があります(このドキュメントの最後にある「クリーンアップ」セクションをご覧ください)。

Google Cloud Platform の新規ユーザーは 300 ドル分の無料トライアルをご利用いただけます。

Google Cloud Shell をアクティブにする

GCP Console で右上のツールバーにある Cloud Shell アイコンをクリックします。

[Cloud Shell の起動] をクリックします。

プロビジョニングと環境への接続にはそれほど時間はかかりません。

この仮想マシンには、必要な開発ツールがすべて準備されています。5 GB の永続ホーム ディレクトリが用意されており、Google Cloud で稼働するため、ネットワーク パフォーマンスが充実しており認証もスムーズです。このラボでの作業のほとんどは、ブラウザまたは Google Chromebook から実行できます。

Cloud Shell に接続されると、認証が完了し、プロジェクトが PROJECT_ID に設定されていることが確認できます。

Cloud Shell で次のコマンドを実行して、認証されたことを確認します。

gcloud auth list

コマンド出力

Credentialed accounts:
 - <myaccount>@<mydomain>.com (active)
gcloud config list project

コマンド出力

[core]
project = <PROJECT_ID>

上記のようになっていない場合は、次のコマンドで設定できます。

gcloud config set project <PROJECT_ID>

コマンド出力

Updated property [core/project].

GCP Console で、[メニュー] - [Datastore]([ストレージ] 内)に移動します。

現在のプロジェクトで Datastore を初めて使用する場合は、[Cloud Firestore モードの選択] 画面が表示されます。[Datastore モード] オプションを選択します。

保存すると、[データの保存場所の選択] 画面が表示されます。us-east1 またはその他のリージョン ロケーションを選択して、[データベースを作成] をクリックします。

CloudShell 環境から次のコマンドを使用して、新しい Spring Boot アプリケーションを初期化、ブートストラップします。

$ curl https://start.spring.io/starter.tgz \
  -d packaging=war \
  -d dependencies=cloud-gcp \
  -d baseDir=datastore-example \
  -d bootVersion=2.1.1.RELEASE | tar -xzvf -

これにより、新しい Maven プロジェクトを含む新しい datastore-example/ ディレクトリ、Maven の pom.xml、Maven ラッパー、アプリケーション エントリポイントが作成されます。

アプリケーションは、ユーザーがコマンドを入力して結果を確認するための CLI を提供します。書籍を表すクラスを作成し、Datastore リポジトリを使用して Cloud Datastore に保存します。

また、pom.xml に必要な依存関係を 1 つ追加する必要があります。

Cloud Shell メニューで [コードエディタの起動] をクリックして、ウェブコード エディタを開きます。

エディタが読み込まれたら、pom.xml ファイルを変更して Spring Data Cloud Datastore Spring Boot スターター依存関係を追加します。

pom.xml

<project>
  ...
  <dependencies>
        ...
        <!-- Add GCP Datastore Starter -->
        <dependency>
                <groupId>org.springframework.cloud</groupId>          
                <artifactId>spring-cloud-gcp-starter-data-datastore</artifactId>
        </dependency>

        <!-- Add Spring Shell Starter -->
        <dependency>
                <groupId>org.springframework.shell</groupId>
                <artifactId>spring-shell-starter</artifactId>
                <version>2.0.0.RELEASE</version>
        </dependency>

  </dependencies>
</project>

エディタを使用して、次の内容の Book クラスを作成します。

datastore-example/src/main/java/com/example/demo/Book.java

package com.example.demo;

import org.springframework.cloud.gcp.data.datastore.core.mapping.Entity;
import org.springframework.data.annotation.Id;


@Entity(name = "books")
public class Book {
        @Id
        Long id;

        String title;

        String author;

        int year;

        public Book(String title, String author, int year) {
                this.title = title;
                this.author = author;
                this.year = year;
        }

        public long getId() {
                return this.id;
        }

        @Override
        public String toString() {
                return "Book{" +
                                "id=" + this.id +
                                ", title='" + this.title + '\'' +
                                ", author='" + this.author + '\'' +
                                ", year=" + this.year +
                                '}';
        }
}

ご覧のように、シンプルな POJO です。クラスに @Entity アノテーションが付けられ、これが Datastore に保存できることを示すとともに種類名を指定できるようになりました(種類は SQL データベースのテーブルと考えてください。詳しくはドキュメントをご覧ください)。種類名は省略可能です。省略した場合は、クラス名に基づいて種類名が生成されます。

id プロパティ@Id アノテーションを付けています。これは、このフィールドを Datastore キーの識別子部分として使用することを示します。すべての Datastore エンティティには識別子が必要です。サポートされている型は StringLong です。

toString メソッドをオーバーライドして、オブジェクトの文字列表現を読みやすくします。これは、オブジェクトを印刷するときに便利です。

忘れずにファイルを保存してください。

次の内容の BookRepository クラスを作成します。

datastore-example/src/main/java/com/example/demo/BookRepository.java

package com.example.demo;

import java.util.List;

import org.springframework.cloud.gcp.data.datastore.repository.DatastoreRepository;


public interface BookRepository extends DatastoreRepository<Book, Long> {

  List<Book> findByAuthor(String author);

  List<Book> findByYearGreaterThan(int year);

  List<Book> findByAuthorAndYear(String author, int year);

}

このインターフェースは DatastoreRepository<Book, Long> を拡張します。Book はドメインクラス、LongId 型です。Google のリポジトリでは、背後で自動的に実装される 3 つのクエリメソッドを宣言しています。

1 件目はfindByAuthorです。ご想像のとおり、このメソッドの実装では、条件フィルタでユーザー指定の値を「著者と等しい」フィールドに使用するクエリを実行します。

findByYearGreaterThan メソッドは、ユーザーが指定した値よりも大きい年のフィールドをフィルタリングするクエリを実行します。

findByAuthorAndYear は、author フィールドと year フィールドがユーザー指定の値と一致するエンティティを検索するクエリを実行します。

メイン アプリケーション DemoApplication クラスを開き、次のように変更します。

datastore-example/src/main/java/com/example/demo/DemoApplication.java

package com.example.demo;

import java.util.List;

import com.google.common.collect.Lists;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

@ShellComponent
@SpringBootApplication
public class DemoApplication {
  @Autowired
  BookRepository bookRepository;

  public static void main(String[] args) {
     SpringApplication.run(DemoApplication.class, args);
  }

  @ShellMethod("Saves a book to Cloud Datastore: save-book <title> <author> <year>")
  public String saveBook(String title, String author, int year) {
     Book savedBook = this.bookRepository.save(new Book(title, author, year));
     return savedBook.toString();
  }

  @ShellMethod("Loads all books")
  public String findAllBooks() {
     Iterable<Book> books = this.bookRepository.findAll();
     return Lists.newArrayList(books).toString();
  }

  @ShellMethod("Loads books by author: find-by-author <author>")
  public String findByAuthor(String author) {
     List<Book> books = this.bookRepository.findByAuthor(author);
     return books.toString();
  }

  @ShellMethod("Loads books published after a given year: find-by-year-after <year>")
  public String findByYearAfter(int year) {
     List<Book> books = this.bookRepository.findByYearGreaterThan(year);
     return books.toString();
  }

  @ShellMethod("Loads books by author and year: find-by-author-year <author> <year>")
  public String findByAuthorYear(String author, int year) {
     List<Book> books = this.bookRepository.findByAuthorAndYear(author, year);
     return books.toString();
  }

  @ShellMethod("Removes all books")
  public void removeAllBooks() {
     this.bookRepository.deleteAll();
  }
}

クラスに @ShellComponent アノテーションが付けられていることに注意してください。これにより、このクラスを CLI コマンドのソースとして使用することが Spring に通知されます。@ShellMethod アノテーションが付けられたメソッドは、アプリケーションで CLI コマンドとして公開されます。

ここでは、BookRepository インターフェースで宣言したメソッド(findByAuthorfindByYearGreaterThanfindByAuthorAndYear)を使用します。また、savefindAlldeleteAll の 3 つの組み込みメソッドを使用しています。

saveBook メソッドを見てみましょう。タイトル、著者、年のユーザー指定の値を使用して、Book オブジェクトを作成します。ご覧のとおり、id 値は提供されていないため、自動的に保存されて id フィールドに割り当てられます。save メソッドは、Book 型のオブジェクトを受け入れ、Cloud Datastore に保存します。id フィールドを含むすべてのフィールドが入力された Book オブジェクトを返します。最終的に、このオブジェクトの文字列表現を返します。

残りのメソッドも同様に、パラメータを渡されたリポジトリ メソッドに渡すパラメータを受け取って、文字列化された結果を返します。

アプリケーションをビルドして起動するには、(pom.xml が配置されているプロジェクト datastore-example/ のルートから)Cloud Shell で次のコマンドを実行します。

$ mvn spring-boot:run

ビルドステージが成功すると、Spring のロゴが表示され、シェル プロンプトが表示されます。

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.1.RELEASE)


shell:> 

これで、前に定義したコマンドを試すことができます。コマンドの一覧を表示するには、help コマンドを使用します。

shell:> help
...
find-all-books: Loads all books
find-by-author: Loads books by author: find-by-author <author>
find-by-author-year: Loads books by author and year: find-by-author-year <author> <year>
find-by-year-after: Loads books published after a given year: find-by-year-after <year>
remove-all-books: Removes all books
save-book: Saves a book to Cloud Datastore: save-book <title> <author> <year>

次のようにしてください。

  1. save-book コマンドを使って書籍をいくつか作成する
  2. find-all-books コマンドを使用して検索を実行する
  3. 特定の著者(find-by-author <author>)の書籍を検索する
  4. 特定の年以降に出版された書籍を探す(find-by-year-after <year>
  5. 特定の著者と年の書籍を探す(find-by-author-year <author> <year>

エンティティが Cloud Datastore にどのように格納されているかを確認するには、GCP Console で、[メニュー] -> [Datastore]([Storage] セクション内) -> エンティティに移動します(必要に応じて、[default] 名前空間と [books] 種類を選択してください)。

クリーンアップするには、適切な名前の remove-all-books コマンドを使用して、アプリケーション シェルからすべての書籍を削除します。

shell:> remove-all-books

アプリケーションを終了するには、終了コマンドを使用し、Ctrl+C キーを押します。

この Codelab では、Cloud Datastore でオブジェクトを保存および取得できるインタラクティブな CLI アプリケーションを作成しました。

詳細

ライセンス

この作業はクリエイティブ・コモンズの表示 2.0 汎用ライセンスにより使用許諾されています。