Crea una pipeline Dataflow utilizzando Java

Questo documento mostra come configurare il progetto, creare una pipeline di esempio creata con l'SDK Apache Beam per Java ed eseguire la pipeline di esempio nel servizio Dataflow. Google Cloud La pipeline legge un file di testo da Cloud Storage, conta il numero di parole uniche nel file e poi scrive i conteggi delle parole in Cloud Storage. Per un'introduzione alla pipeline WordCount, guarda il video Come utilizzare WordCount in Apache Beam.

Questo tutorial richiede Maven, ma è anche possibile convertire il progetto di esempio da Maven a Gradle. Per scoprire di più, consulta (Facoltativo) Convertire da Maven a Gradle.


Per seguire le indicazioni dettagliate per questa attività direttamente nella Google Cloud console, fai clic su Procedura guidata:

Procedura guidata


Prima di iniziare

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Install the Google Cloud CLI.

  3. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  4. To initialize the gcloud CLI, run the following command:

    gcloud init
  5. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Dataflow, Compute Engine, Cloud Logging, Cloud Storage, Google Cloud Storage JSON, BigQuery, Cloud Pub/Sub, Cloud Datastore, and Cloud Resource Manager APIs:

    gcloud services enable dataflow compute_component logging storage_component storage_api bigquery pubsub datastore.googleapis.com cloudresourcemanager.googleapis.com
  8. Create local authentication credentials for your user account:

    gcloud auth application-default login

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

  9. Grant roles to your user account. Run the following command once for each of the following IAM roles: roles/iam.serviceAccountUser

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE
    • Replace PROJECT_ID with your project ID.
    • Replace USER_IDENTIFIER with the identifier for your user account. For example, user:myemail@example.com.

    • Replace ROLE with each individual role.
  10. Install the Google Cloud CLI.

  11. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  12. To initialize the gcloud CLI, run the following command:

    gcloud init
  13. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  14. Make sure that billing is enabled for your Google Cloud project.

  15. Enable the Dataflow, Compute Engine, Cloud Logging, Cloud Storage, Google Cloud Storage JSON, BigQuery, Cloud Pub/Sub, Cloud Datastore, and Cloud Resource Manager APIs:

    gcloud services enable dataflow compute_component logging storage_component storage_api bigquery pubsub datastore.googleapis.com cloudresourcemanager.googleapis.com
  16. Create local authentication credentials for your user account:

    gcloud auth application-default login

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

  17. Grant roles to your user account. Run the following command once for each of the following IAM roles: roles/iam.serviceAccountUser

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE
    • Replace PROJECT_ID with your project ID.
    • Replace USER_IDENTIFIER with the identifier for your user account. For example, user:myemail@example.com.

    • Replace ROLE with each individual role.
  18. Concedi ruoli al account di servizio Compute Engine predefinito. Esegui il seguente comando una volta per ciascuno dei seguenti ruoli IAM:

    • roles/dataflow.admin
    • roles/dataflow.worker
    • roles/storage.objectAdmin
    gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com" --role=SERVICE_ACCOUNT_ROLE
    • Sostituisci PROJECT_ID con l'ID progetto.
    • Sostituisci PROJECT_NUMBER con il numero del tuo progetto. Per trovare il numero del progetto, consulta Identificare i progetti o utilizza il comando gcloud projects describe.
    • Sostituisci SERVICE_ACCOUNT_ROLE con ogni singolo ruolo.
  19. Create a Cloud Storage bucket and configure it as follows:
    • Set the storage class to S (Standard).
    • Imposta la posizione di archiviazione su: US (Stati Uniti).
    • Sostituisci BUCKET_NAME con un nome di bucket univoco. Non includere informazioni sensibili nel nome del bucket perché lo spazio dei nomi dei bucket è globale e visibile pubblicamente.
    • gcloud storage buckets create gs://BUCKET_NAME --default-storage-class STANDARD --location US
    • Copia quanto segue, perché ti servirà in una sezione successiva:
    • Scarica e installa la versione 11 del Java Development Kit (JDK). (Dataflow continua a supportare la versione 8.) Verifica che la variabile di ambiente JAVA_HOME sia impostata e punti all'installazione di JDK.
    • Scarica e installa Apache Maven seguendo la guida all'installazione di Maven per il tuo sistema operativo specifico.

Recupera il codice della pipeline

L' SDK Apache Beam è un modello di programmazione open source per pipeline di elaborazione dati. Definisci queste pipeline con un programma Apache Beam e puoi scegliere un runner, ad esempio Dataflow, per eseguire la pipeline.

  1. Nella shell o nel terminale, utilizza il plug-in Maven Archetype per creare un progetto Maven sul computer che contenga gli esempi WordCount dell'SDK Apache Beam:
    mvn archetype:generate \
        -DarchetypeGroupId=org.apache.beam \
        -DarchetypeArtifactId=beam-sdks-java-maven-archetypes-examples \
        -DarchetypeVersion=2.66.0 \
        -DgroupId=org.example \
        -DartifactId=word-count-beam \
        -Dversion="0.1" \
        -Dpackage=org.apache.beam.examples \
        -DinteractiveMode=false
    

    Il comando crea una nuova directory denominata word-count-beam nella directory corrente. La directory word-count-beam contiene un semplice file pom.xml e una serie di pipeline di esempio che contano le parole nei file di testo.

  2. Verifica che la directory word-count-beam contenga il file pom.xml:

    Linux o macOS

    cd word-count-beam/
    ls

    L'output è il seguente:

    pom.xml   src

    Windows

    cd word-count-beam/
    dir

    L'output è il seguente:

    pom.xml   src
  3. Verifica che il progetto Maven contenga le pipeline di esempio:

    Linux o macOS

    ls src/main/java/org/apache/beam/examples/

    L'output è il seguente:

    DebuggingWordCount.java   WindowedWordCount.java   common
    MinimalWordCount.java   WordCount.java

    Windows

    dir src/main/java/org/apache/beam/examples/

    L'output è il seguente:

    DebuggingWordCount.java   WindowedWordCount.java   common
    MinimalWordCount.java   WordCount.java

Per un'introduzione dettagliata ai concetti di Apache Beam utilizzati in questi esempi, consulta l'esempio WordCount di Apache Beam. Le istruzioni nelle sezioni successive utilizzano WordCount.java.

Esegui la pipeline in locale

  • Nella shell o nel terminale, esegui la pipeline WordCount in locale dalla directory word-count-beam:
    mvn compile exec:java \
        -Dexec.mainClass=org.apache.beam.examples.WordCount \
        -Dexec.args="--output=counts"
    

    I file di output hanno il prefisso counts e vengono scritti nella directory word-count-beam. Contengono parole uniche del testo di input e il numero di occorrenze di ciascuna parola.

Esegui la pipeline sul servizio Dataflow

  • Nella shell o nel terminale, crea ed esegui la pipeline WordCount sul servizio Dataflow dalla directory word-count-beam:
    mvn -Pdataflow-runner compile exec:java \
        -Dexec.mainClass=org.apache.beam.examples.WordCount \
        -Dexec.args="--project=PROJECT_ID \
        --gcpTempLocation=gs://BUCKET_NAME/temp/ \
        --output=gs://BUCKET_NAME/output \
        --runner=DataflowRunner \
        --region=REGION"
    

    Sostituisci quanto segue:

    • PROJECT_ID: il tuo ID progetto Google Cloud
    • BUCKET_NAME: il nome del bucket Cloud Storage
    • REGION: una regione Dataflow, ad esempio us-central1

Visualizza i tuoi risultati

  1. Nella console Google Cloud , vai alla pagina Job di Dataflow.

    Vai a Job

    La pagina Job mostra i dettagli di tutti i job disponibili, incluso lo stato. Lo stato del job wordcount è inizialmente In esecuzione, poi viene aggiornato a Riuscito.

  2. Nella console Google Cloud , vai alla pagina Bucket in Cloud Storage.

    Vai a Bucket

    La pagina Bucket mostra l'elenco di tutti i bucket di archiviazione del tuo progetto.

  3. Fai clic sul bucket di archiviazione che hai creato.

    La pagina Dettagli bucket mostra i file di output e di staging creati dal job Dataflow.

Esegui la pulizia

Per evitare che al tuo account Google Cloud vengano addebitati costi relativi alle risorse utilizzate in questa pagina, elimina il progetto Google Cloud con le risorse.

Elimina il progetto

Il modo più semplice per eliminare la fatturazione è eliminare il progetto che hai creato per la guida rapida. Google Cloud

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

Elimina le singole risorse

Se vuoi conservare il progetto Google Cloud che hai utilizzato in questa guida rapida, elimina le singole risorse:

  1. In the Google Cloud console, go to the Cloud Storage Buckets page.

    Go to Buckets

  2. Click the checkbox for the bucket that you want to delete.
  3. To delete the bucket, click Delete, and then follow the instructions.
  4. Revoca i ruoli che hai concesso al account di servizio Compute Engine predefinito. Esegui il seguente comando una volta per ciascuno dei seguenti ruoli IAM:

    • roles/dataflow.admin
    • roles/dataflow.worker
    • roles/storage.objectAdmin
    gcloud projects remove-iam-policy-binding PROJECT_ID \
        --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com \
        --role=SERVICE_ACCOUNT_ROLE
  5. Optional: Revoke the authentication credentials that you created, and delete the local credential file.

    gcloud auth application-default revoke
  6. Optional: Revoke credentials from the gcloud CLI.

    gcloud auth revoke

Passaggi successivi