Utilizzo di Cloud Firestore in modalità Datastore

Firestore è un database di documenti NoSQL creato per offrire scalabilità automatica, prestazioni elevate e facilità dello sviluppo di applicazioni. Si tratta della versione più recente di Datastore e introduce diversi miglioramenti rispetto a Datastore.

Poiché Firestore in modalità Datastore è ottimizzato per casi d'uso del server e per App Engine, consigliamo di utilizzare Firestore in modalità Datastore per database che verranno utilizzati principalmente dalle app di App Engine. Firestore in modalità nativa è più utile per i casi d'uso delle notifiche su dispositivi mobili e in tempo reale. Per ulteriori informazioni sulle modalità Firestore, consulta la pagina relativa alla scelta tra la modalità nativa e la modalità Datastore.

Questo documento descrive come utilizzare la libreria client di Google Cloud per archiviare e recuperare i dati in un database in modalità Datastore.

Prerequisiti e configurazione

Segui le istruzioni in Un saluto da Google, World! per Go su App Engine per configurare l'ambiente e il progetto, nonché per comprendere la struttura delle app Go in App Engine. Annota e salva l'ID progetto, perché ti servirà per eseguire l'applicazione di esempio descritta in questo documento.

Clonare il repository

Scarica (clona) il campione:

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

Modifica la configurazione del progetto e imposta le dipendenze

In app.yaml, imposta GCLOUD_DATASET_ID per il tuo progetto. Questo valore è l'ID progetto.

# 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

Codice dell'applicazione

L'applicazione di esempio registra, recupera e visualizza gli indirizzi IP dei visitatori. Puoi notare che una voce di log è una semplice classe a due campi che riceve il tipo visit, e viene salvata in modalità Datastore utilizzando il comando put del client di Datastore. Quindi, le dieci visite più recenti vengono recuperate in ordine decrescente in base ai comandi NewQuery e GetAll del client Datastore.


// 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 file in uso

L'app di esempio esegue semplici query. Le query più elaborate in modalità Datastore richiedono uno o più indici, che devono essere specificati in un file index.yaml che si carica insieme all'app. Questo file può essere creato manualmente o generato automaticamente durante il test dell'app in locale.

Test locale

Se devi sviluppare e testare la tua applicazione in locale, puoi utilizzare l'emulatore di modalità Datastore.

Per ulteriori informazioni

Per informazioni complete sulla modalità Datastore, tra cui ottimizzazioni e concetti, consulta la documentazione di Cloud Firestore in modalità Datastore.