Cloud Datastore를 사용하는 Spring Boot 애플리케이션

Google Cloud Datastore는 자동 확장, 고성능, 간편한 애플리케이션 개발을 위해 빌드된 NoSQL 문서 데이터베이스입니다.

학습할 내용

  • Cloud Datastore를 사용하여 Spring Boot에서 자바 객체를 저장하고 검색하는 방법

필요한 항목

  • Google Cloud Platform 프로젝트
  • 브라우저(예: Chrome 또는 Firefox)

본 가이드를 어떻게 사용하실 계획인가요?

읽기만 할 계획입니다 읽은 다음 연습 활동을 완료할 계획입니다

귀하의 Google Cloud Platform 서비스 사용 경험을 평가해 주세요.

초급 중급 고급

자습형 환경 설정

Google 계정 (Gmail 또는 Google 앱)이 아직 없다면 계정을 만들어야 합니다. Google Cloud Platform Console (console.cloud.google.com)에 로그인하여 새 프로젝트를 만듭니다.

2016-02-10 12:45:26.png 스크린샷

모든 Google Cloud 프로젝트에서 고유한 이름인 프로젝트 ID를 기억하세요(위의 이름은 이미 사용되었으므로 사용할 수 없습니다). 이 ID는 나중에 이 Codelab에서 PROJECT_ID라고 부릅니다.

다음으로 Google Cloud 리소스를 사용하려면 Cloud Console에서 결제를 사용 설정해야 합니다.

이 codelab을 실행하는 과정에는 많은 비용이 들지 않지만 더 많은 리소스를 사용하려고 하거나 실행 중일 경우 비용이 더 들 수 있습니다(이 문서 마지막의 '삭제' 섹션 참조).

Google Cloud Platform의 신규 사용자는 $300 무료 체험판을 사용할 수 있습니다.

Google Cloud Shell 활성화

GCP 콘솔에서 오른쪽 상단 툴바의 Cloud Shell 아이콘을 클릭합니다.

그런 다음 'Cloud Shell 시작'을 클릭합니다.

환경을 프로비저닝하고 연결하는 데 몇 분 정도 소요됩니다.

가상 머신은 필요한 모든 개발 도구와 함께 로드됩니다. 영구적인 5GB 홈 디렉토리를 제공하고 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 mode" 옵션을 선택합니다.

그러면 "데이터 저장 위치 선택& 화면이 표시됩니다. us-east1 또는 다른 리전 위치를 선택하고 "Create Database"를 클릭합니다.

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에 필요한 종속 항목을 하나 더 추가해야 합니다.

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은 구현이 백그라운드에서 자동으로 생성되는 쿼리 메서드 세 개를 선언합니다.

첫 번째 항목은 findByAuthor입니다. 짐작하시다시피 이 메서드의 구현은 조건 동등성 조건 조건의 사용자 제공 값을 사용하는 쿼리를 실행합니다.

findByYearGreaterThan 메서드는 사용자 제공 값보다 큰 연도 필드를 필터링하는 쿼리를 실행합니다.

findByAuthorAndYear은 작성자 및 연도 필드가 사용자 제공 값과 일치하는 항목을 찾는 쿼리를 실행합니다.

기본 애플리케이션 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 주석을 어떻게 추가했는지 확인하세요. Spring에 이 클래스를 CLI 명령어의 소스로 사용하라고 Spring에 알립니다. @ShellMethod 주석이 달린 메서드는 애플리케이션에서 CLI 명령어로 노출됩니다.

여기서는 BookRepository 인터페이스에서 선언한 메서드인 findByAuthor, findByYearGreaterThan, findByAuthorAndYear를 사용합니다. 또한 세 가지 기본 제공 메서드 save, findAll, deleteAll을 사용합니다.

saveBook 메서드를 살펴보겠습니다. 제목, 저자, 연도에 사용자가 제공한 값을 사용하여 Book 객체를 만듭니다. 보시다시피 id 값은 제공하지 않으므로 저장 시 ID 필드에 자동으로 할당되고 할당됩니다. save 메서드는 Book 유형의 객체를 수락하고 Cloud Datastore에 저장합니다. 이 필드는 id 필드를 비롯하여 모든 필드가 채워진 Book 객체를 반환합니다. 마지막에는 이 객체의 문자열 표현을 반환합니다.

나머지 메서드는 유사하게 작동합니다. 즉, 적절한 저장소 메서드에 전달된 매개변수를 허용하고 문자열화된 결과를 반환합니다.

애플리케이션을 빌드하고 시작하려면 pom.xml이 있는 datastore-example/ 프로젝트의 루트에서 Cloud Shell에서 다음 명령어를 실행합니다.

$ mvn spring-boot:run

빌드 단계가 완료되면 스프링 로고가 표시되고 셸 프롬프트가 표시됩니다.

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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 - 스토리지 섹션 -> 항목(필요한 경우 'default'" 네임스페이스 선택 및 "books" 종류)으로 이동하세요.

정리하려면 애플리케이션 셸에서 remove-all-books 명령어를 사용하여 모든 책을 삭제합니다.

shell:> remove-all-books

애플리케이션을 종료하려면 exit 명령어를 사용한 다음 Ctrl+C를 누릅니다.

이 Codelab에서는 Cloud Datastore에서 객체를 저장하고 검색할 수 있는 대화형 CLI 애플리케이션을 만들었습니다.

자세히 알아보기

라이선스

이 작업물은 Creative Commons Attribution 2.0 일반 라이선스에 따라 사용이 허가되었습니다.