Datastore 모드로 Cloud Firestore 사용

Firestore는 자동 확장, 고성능, 간편한 애플리케이션 개발을 위해 설계된 NoSQL 문서 데이터베이스입니다. Datastore의 최신 버전이며 Datastore에 비해 여러 가지 부분이 개선되었습니다.

Datastore 모드의 Firestore는 서버 사용 사례 및 App Engine에 최적화되어 있으므로 App Engine 앱에서 주로 사용하는 데이터베이스에는 Datastore 모드의 Firestore를 사용하는 것이 좋습니다. 기본 모드의 Firestore는 모바일 및 실시간 알림 사용 사례에 가장 유용합니다. Firestore 모드에 대한 자세한 내용은 Native 모드와 Datastore 모드 중 선택을 참조하세요.

이 문서에서는 Google Cloud 클라이언트 라이브러리를 사용하여 Datastore 모드 데이터베이스에서 데이터를 저장하고 검색하는 방법을 설명합니다.

기본 요건 및 설정

App Engine에서 Go용 'Hello, World!'의 안내에 따라 환경과 프로젝트를 설정하고 Go 앱이 App Engine에서 구조화되는 방식을 이해합니다. 이 문서에 설명된 샘플 애플리케이션을 실행할 때 필요하므로 프로젝트 ID를 기록해 둡니다.

저장소 복제

샘플을 다운로드(복제)합니다.

go get -d -v github.com/GoogleCloudPlatform/golang-samples/datastore
cd $GOPATH/src/github.com/GoogleCloudPlatform/golang-samples/appengine_flexible/datastore

프로젝트 구성 수정 및 종속성 설정

app.yaml에서 프로젝트에 GCLOUD_DATASET_ID를 설정합니다. 이 값은 프로젝트 ID입니다.

# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

runtime: go
env: flex

automatic_scaling:
  min_num_instances: 1

env_variables:
  GCLOUD_DATASET_ID: your-project-id

애플리케이션 코드

샘플 애플리케이션은 방문자 IP를 로깅, 검색, 표시합니다. 로그 항목은 visit 유형이 지정된 단순한 2개 필드로 이루어진 클래스이며 Datastore 클라이언트 put 명령어를 사용하여 Datastore에 저장되는 것을 확인할 수 있습니다. 이후 Datastore 클라이언트 NewQueryGetAll 명령어를 사용하면 최근 방문 내용이 10개까지 내림차순으로 검색됩니다.


// Sample datastore demonstrates use of the cloud.google.com/go/datastore package from App Engine flexible.
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"cloud.google.com/go/datastore"
	"google.golang.org/appengine"
)

var datastoreClient *datastore.Client

func main() {
	ctx := context.Background()

	// Set this in app.yaml when running in production.
	projectID := os.Getenv("GCLOUD_DATASET_ID")

	var err error
	datastoreClient, err = datastore.NewClient(ctx, projectID)
	if err != nil {
		log.Fatal(err)
	}

	http.HandleFunc("/", handle)
	appengine.Main()
}

func handle(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}

	ctx := context.Background()

	// Get a list of the most recent visits.
	visits, err := queryVisits(ctx, 10)
	if err != nil {
		msg := fmt.Sprintf("Could not get recent visits: %v", err)
		http.Error(w, msg, http.StatusInternalServerError)
		return
	}

	// Record this visit.
	if err := recordVisit(ctx, time.Now(), r.RemoteAddr); err != nil {
		msg := fmt.Sprintf("Could not save visit: %v", err)
		http.Error(w, msg, http.StatusInternalServerError)
		return
	}

	fmt.Fprintln(w, "Previous visits:")
	for _, v := range visits {
		fmt.Fprintf(w, "[%s] %s\n", v.Timestamp, v.UserIP)
	}
	fmt.Fprintln(w, "\nSuccessfully stored an entry of the current request.")
}

type visit struct {
	Timestamp time.Time
	UserIP    string
}

func recordVisit(ctx context.Context, now time.Time, userIP string) error {
	v := &visit{
		Timestamp: now,
		UserIP:    userIP,
	}

	k := datastore.IncompleteKey("Visit", nil)

	_, err := datastoreClient.Put(ctx, k, v)
	return err
}

func queryVisits(ctx context.Context, limit int64) ([]*visit, error) {
	// Print out previous visits.
	q := datastore.NewQuery("Visit").
		Order("-Timestamp").
		Limit(10)

	visits := make([]*visit, 0)
	_, err := datastoreClient.GetAll(ctx, q, &visits)
	return visits, err
}

index.yaml 파일 사용

샘플 앱에서는 간단한 쿼리를 수행합니다. 보다 정교한 Datastore 모드 쿼리를 실행하려면 색인이 한 개 이상 필요하며 앱과 함께 업로드하는 index.yaml 파일에서 색인을 지정해야 합니다. 이 파일은 수동으로 만들거나 로컬에서 앱을 테스트하는 동안 자동으로 생성될 수 있습니다.

로컬 테스트

로컬에서 애플리케이션을 개발하고 테스트해야 하는 경우 Datastore 모드 에뮬레이터를 사용할 수 있습니다.

추가 정보

최적화와 개념을 비롯하여 Datastore 모드에 대한 자세한 내용은 Datastore 모드 문서의 Firestore를 참조하세요.