Apache Kafka ist eine verteilte Open-Source-Streamingplattform für Echtzeit-Datenpipelines und Datenintegration. Es bietet ein effizientes und skalierbares Streaming-System für eine Vielzahl von Anwendungen, darunter:
- Echtzeitanalysen
- Streamverarbeitung
- Logaggregation
- Verteilte Nachrichten
- Event-Streaming
Lernziele
Installieren Sie Kafka auf einem Dataproc-Cluster für hohe Verfügbarkeit mit ZooKeeper (in dieser Anleitung als „Dataproc-Kafka-Cluster“ bezeichnet).
Erstellen Sie fiktive Kundendaten und veröffentlichen Sie die Daten dann in einem Kafka-Thema.
Erstellen Sie Hive-Parquet- und ORC-Tabellen in Cloud Storage, um gestreamte Kafka-Themendaten zu empfangen.
Senden Sie einen PySpark-Job, um das Kafka-Thema zu abonnieren und in Cloud Storage im Parquet- und ORC-Format zu streamen.
Führen Sie eine Abfrage für die gestreamten Hive-Tabellendaten aus, um die gestreamten Kafka-Nachrichten zu zählen.
Kosten
In diesem Dokument verwenden Sie die folgenden kostenpflichtigen Komponenten von Google Cloud:
Mit dem Preisrechner können Sie eine Kostenschätzung für Ihre voraussichtliche Nutzung vornehmen.
Nach Abschluss der in diesem Dokument beschriebenen Aufgaben können Sie weitere Kosten vermeiden, indem Sie die erstellten Ressourcen löschen. Weitere Informationen finden Sie unter Bereinigen.
Hinweise
Falls Sie es noch nicht getan haben, erstellen Sie ein Google Cloud Projekt.
- 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.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Dataproc, Compute Engine, and Cloud Storage APIs.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Dataproc, Compute Engine, and Cloud Storage APIs.
- In the Google Cloud console, go to the Cloud Storage Buckets page.
- Click Create.
- On the Create a bucket page, enter your bucket information. To go to the next
step, click Continue.
-
In the Get started section, do the following:
- Enter a globally unique name that meets the bucket naming requirements.
- To add a
bucket label,
expand the Labels section ( ),
click add_box
Add label, and specify a
key
and avalue
for your label.
-
In the Choose where to store your data section, do the following:
- Select a Location type.
- Choose a location where your bucket's data is permanently stored from the Location type drop-down menu.
- If you select the dual-region location type, you can also choose to enable turbo replication by using the relevant checkbox.
- To set up cross-bucket replication, select
Add cross-bucket replication via Storage Transfer Service and
follow these steps:
Set up cross-bucket replication
- In the Bucket menu, select a bucket.
In the Replication settings section, click Configure to configure settings for the replication job.
The Configure cross-bucket replication pane appears.
- To filter objects to replicate by object name prefix, enter a prefix that you want to include or exclude objects from, then click Add a prefix.
- To set a storage class for the replicated objects, select a storage class from the Storage class menu. If you skip this step, the replicated objects will use the destination bucket's storage class by default.
- Click Done.
-
In the Choose how to store your data section, do the following:
- Select a default storage class for the bucket or Autoclass for automatic storage class management of your bucket's data.
- To enable hierarchical namespace, in the Optimize storage for data-intensive workloads section, select Enable hierarchical namespace on this bucket.
- In the Choose how to control access to objects section, select whether or not your bucket enforces public access prevention, and select an access control method for your bucket's objects.
-
In the Choose how to protect object data section, do the
following:
- Select any of the options under Data protection that you
want to set for your bucket.
- To enable soft delete, click the Soft delete policy (For data recovery) checkbox, and specify the number of days you want to retain objects after deletion.
- To set Object Versioning, click the Object versioning (For version control) checkbox, and specify the maximum number of versions per object and the number of days after which the noncurrent versions expire.
- To enable the retention policy on objects and buckets, click the Retention (For compliance) checkbox, and then do the following:
- To enable Object Retention Lock, click the Enable object retention checkbox.
- To enable Bucket Lock, click the Set bucket retention policy checkbox, and choose a unit of time and a length of time for your retention period.
- To choose how your object data will be encrypted, expand the Data encryption section (Data encryption method. ), and select a
- Select any of the options under Data protection that you
want to set for your bucket.
-
In the Get started section, do the following:
- Click Create.
Sehen Sie sich den Code an.
Kopieren Sie das
kafka.sh
-Skript für die Initialisierungsaktion in Ihren Cloud Storage-Bucket. Mit diesem Skript wird Kafka auf einem Dataproc-Cluster installiert.Öffnen Sie Cloud Shell und führen Sie den folgenden Befehl aus:
gcloud storage cp gs://goog-dataproc-initialization-actions-REGION/kafka/kafka.sh gs://BUCKET_NAME/scripts/
Ersetzen Sie die folgenden Werte:
- REGION:
kafka.sh
wird in öffentlichen, regional gekennzeichneten Buckets in Cloud Storage gespeichert. Geben Sie eine geografisch nahe Compute Engine-Region an (z. B.us-central1
). - BUCKET_NAME: Der Name Ihres Cloud Storage-Buckets
- REGION:
Öffnen Sie Cloud Shell und führen Sie den folgenden
gcloud dataproc clusters create
-Befehl aus, um einen HA-Cluster-Cluster zu erstellen, in dem die Kafka- und ZooKeeper-Komponenten installiert werden:gcloud dataproc clusters create KAFKA_CLUSTER \ --project=PROJECT_ID \ --region=REGION \ --image-version=2.1-debian11 \ --num-masters=3 \ --enable-component-gateway \ --initialization-actions=gs://BUCKET_NAME/scripts/kafka.sh
Hinweise:
- KAFKA_CLUSTER: Der Clustername, der innerhalb eines Projekts eindeutig sein muss. Der Name muss mit einem Kleinbuchstaben beginnen und darf bis zu 51 Kleinbuchstaben, Ziffern und Bindestriche enthalten. Sie darf nicht mit einem Bindestrich enden. Der Name eines gelöschten Clusters kann wiederverwendet werden.
- PROJECT_ID: Das Projekt, das diesem Cluster zugeordnet werden soll.
- REGION: Die Compute Engine-Region, in der sich der Cluster befindet, z. B.
us-central1
.- Sie können das optionale Flag
--zone=ZONE
hinzufügen, um eine Zone in der angegebenen Region anzugeben, z. B.us-central1-a
. Wenn Sie keine Zone angeben, wählt die Dataproc-Funktion zur automatischen Zonenplatzierung eine Zone in der angegebenen Region aus.
- Sie können das optionale Flag
--image-version
: Für dieses Tutorial wird die Dataproc-Image-Version2.1-debian11
empfohlen. Hinweis: Jede Image-Version enthält eine Reihe vorinstallierter Komponenten, einschließlich der in dieser Anleitung verwendeten Hive-Komponente (siehe Unterstützte Dataproc-Image-Versionen).--num-master
:3
Masterknoten bilden einen HA-Cluster. Die Zookeeper-Komponente, die für Kafka erforderlich ist, ist in einem HA-Cluster vorinstalliert.--enable-component-gateway
: Aktiviert das Dataproc Component Gateway.- BUCKET_NAME: Der Name Ihres Cloud Storage-Bucket, der das
/scripts/kafka.sh
-Initialisierungsskript enthält (siehe Kafka-Installationsskript in Cloud Storage kopieren).
Verwenden Sie das SSH-Dienstprogramm, um ein Terminalfenster auf der Master-VM des Clusters zu öffnen.
Erstellen Sie ein Kafka-Thema
custdata
./usr/lib/kafka/bin/kafka-topics.sh \ --bootstrap-server KAFKA_CLUSTER-w-0:9092 \ --create --topic custdata
Hinweise:
KAFKA_CLUSTER: Geben Sie den Namen Ihres Kafka-Clusters ein.
-w-0:9092
steht für den Kafka-Broker, der auf dem Knotenworker-0
auf Port9092
ausgeführt wird.Nachdem Sie das Thema
custdata
erstellt haben, können Sie die folgenden Befehle ausführen:# List all topics. /usr/lib/kafka/bin/kafka-topics.sh \ --bootstrap-server KAFKA_CLUSTER-w-0:9092 \ --list
# Consume then display topic data. /usr/lib/kafka/bin/kafka-console-consumer.sh \ --bootstrap-server KAFKA_CLUSTER-w-0:9092 \ --topic custdata
# Count the number of messages in the topic. /usr/lib/kafka/bin/kafka-run-class.sh kafka.tools.GetOffsetShell \ --broker-list KAFKA_CLUSTER-w-0:9092 \ --topic custdata # Delete topic. /usr/lib/kafka/bin/kafka-topics.sh \ --bootstrap-server KAFKA_CLUSTER-w-0:9092 \ --delete --topic custdata
Kopieren Sie das Skript und fügen Sie es dann im SSH-Terminal auf dem Masterknoten Ihres Kafka-Clusters ein. Drücken Sie die Eingabetaste, um das Skript auszuführen.
for i in {1..10000}; do \ custname="cust name${i}" uuid=$(dbus-uuidgen) age=$((45 + $RANDOM % 45)) amount=$(echo "$(( $RANDOM % 99999 )).$(( $RANDOM % 99 ))") message="${uuid}:${custname},${age},${amount}" echo ${message} done | /usr/lib/kafka/bin/kafka-console-producer.sh \ --broker-list KAFKA_CLUSTER-w-0:9092 \ --topic custdata \ --property "parse.key=true" \ --property "key.separator=:"
Hinweise:
- KAFKA_CLUSTER: Der Name Ihres Kafka-Clusters.
Führen Sie den folgenden Kafka-Befehl aus, um zu prüfen, ob das Thema
custdata
10.000 Nachrichten enthält./usr/lib/kafka/bin/kafka-run-class.sh kafka.tools.GetOffsetShell \ --broker-list KAFKA_CLUSTER-w-0:9092 \ --topic custdata
Hinweise:
- KAFKA_CLUSTER: Der Name Ihres Kafka-Clusters.
Erwartete Ausgabe:
custdata:0:10000
Fügen Sie Ihre BUCKET_NAME in das folgende Skript ein, kopieren Sie es und fügen Sie es in das SSH-Terminal auf dem Masterknoten Ihres Kafka-Clusters ein. Drücken Sie dann die Eingabetaste, um ein
~/hivetables.hql
-Skript (Hive Query Language) zu erstellen.Im nächsten Schritt führen Sie das
~/hivetables.hql
-Skript aus, um Parquet- und ORC-Hive-Tabellen in Ihrem Cloud Storage-Bucket zu erstellen.cat > ~/hivetables.hql <<EOF drop table if exists cust_parquet; create external table if not exists cust_parquet (uuid string, custname string, age string, amount string) row format delimited fields terminated by ',' stored as parquet location "gs://BUCKET_NAME/tables/cust_parquet"; drop table if exists cust_orc; create external table if not exists cust_orc (uuid string, custname string, age string, amount string) row format delimited fields terminated by ',' stored as orc location "gs://BUCKET_NAME/tables/cust_orc"; EOF
Senden Sie im SSH-Terminal auf dem Masterknoten Ihres Kafka-Clusters den
~/hivetables.hql
-Hive-Job, umcust_parquet
- (Parquet) undcust_orc
- (ORC) Hive-Tabellen in Ihrem Cloud Storage-Bucket zu erstellen.gcloud dataproc jobs submit hive \ --cluster=KAFKA_CLUSTER \ --region=REGION \ -f ~/hivetables.hql
Hinweise:
- Die Hive-Komponente ist auf dem Dataproc Kafka-Cluster vorinstalliert. Eine Liste der Hive-Komponentenversionen, die in den kürzlich veröffentlichten 2.1-Images enthalten sind, finden Sie unter 2.1.x-Releaseversionen.
- KAFKA_CLUSTER: Der Name Ihres Kafka-Clusters.
- REGION: Die Region, in der sich Ihr Kafka-Cluster befindet.
- Führen Sie den folgenden Befehl im SSH-Terminal auf dem Masterknoten Ihres Kafka-Clusters aus, um die
kafka-python
-Bibliothek zu installieren. Ein Kafka-Client ist erforderlich, um Daten aus Kafka-Themen in Cloud Storage zu streamen.
pip install kafka-python
Fügen Sie Ihre BUCKET_NAME ein, kopieren Sie den folgenden PySpark-Code und fügen Sie ihn in das SSH-Terminal auf dem Masterknoten Ihres Kafka-Clusters ein. Drücken Sie dann die Eingabetaste, um eine
streamdata.py
-Datei zu erstellen.Das Skript abonniert das Kafka-Thema
custdata
und streamt die Daten dann in Ihre Hive-Tabellen in Cloud Storage. Das Ausgabeforamt, das Parquet oder ORC sein kann, wird als Parameter an das Script übergeben.cat > streamdata.py <<EOF #!/bin/python import sys from pyspark.sql.functions import * from pyspark.sql.types import * from pyspark.sql import SparkSession from kafka import KafkaConsumer def getNameFn (data): return data.split(",")[0] def getAgeFn (data): return data.split(",")[1] def getAmtFn (data): return data.split(",")[2] def main(cluster, outputfmt): spark = SparkSession.builder.appName("APP").getOrCreate() spark.sparkContext.setLogLevel("WARN") Logger = spark._jvm.org.apache.log4j.Logger logger = Logger.getLogger(__name__) rows = spark.readStream.format("kafka") \ .option("kafka.bootstrap.servers", cluster+"-w-0:9092").option("subscribe", "custdata") \ .option("startingOffsets", "earliest")\ .load() getNameUDF = udf(getNameFn, StringType()) getAgeUDF = udf(getAgeFn, StringType()) getAmtUDF = udf(getAmtFn, StringType()) logger.warn("Params passed in are cluster name: " + cluster + " output format(sink): " + outputfmt) query = rows.select (col("key").cast("string").alias("uuid"),\ getNameUDF (col("value").cast("string")).alias("custname"),\ getAgeUDF (col("value").cast("string")).alias("age"),\ getAmtUDF (col("value").cast("string")).alias("amount")) writer = query.writeStream.format(outputfmt)\ .option("path","gs://BUCKET_NAME/tables/cust_"+outputfmt)\ .option("checkpointLocation", "gs://BUCKET_NAME/chkpt/"+outputfmt+"wr") \ .outputMode("append")\ .start() writer.awaitTermination() if __name__=="__main__": if len(sys.argv) < 2: print ("Invalid number of arguments passed ", len(sys.argv)) print ("Usage: ", sys.argv[0], " cluster format") print ("e.g.: ", sys.argv[0], " <cluster_name> orc") print ("e.g.: ", sys.argv[0], " <cluster_name> parquet") main(sys.argv[1], sys.argv[2]) EOF
Führen Sie im SSH-Terminal auf dem Masterknoten Ihres Kafka-Clusters
spark-submit
aus, um Daten in Ihre Hive-Tabellen in Cloud Storage zu streamen.Geben Sie den Namen Ihres KAFKA_CLUSTER und der Ausgabe FORMAT ein, kopieren Sie den folgenden Code und fügen Sie ihn in das SSH-Terminal auf dem Masterknoten Ihres Kafka-Clusters ein. Drücken Sie dann <return>, um den Code auszuführen und die Kafka-
custdata
-Daten im Parquet-Format in Ihre Hive-Tabellen in Cloud Storage zu streamen.spark-submit --packages \ org.apache.spark:spark-streaming-kafka-0-10_2.12:3.1.3,org.apache.spark:spark-sql-kafka-0-10_2.12:3.1.3 \ --conf spark.history.fs.gs.outputstream.type=FLUSHABLE_COMPOSITE \ --conf spark.driver.memory=4096m \ --conf spark.executor.cores=2 \ --conf spark.executor.instances=2 \ --conf spark.executor.memory=6144m \ streamdata.py KAFKA_CLUSTER FORMAT
Hinweise:
- KAFKA_CLUSTER: Geben Sie den Namen Ihres Kafka-Clusters ein.
- FORMAT: Geben Sie entweder
parquet
oderorc
als Ausgabeforamt an. Sie können den Befehl nacheinander ausführen, um beide Formate in die Hive-Tabellen zu streamen. Geben Sie beispielsweise beim ersten Aufrufparquet
an, um das Kafka-Themacustdata
in die Hive-Parquet-Tabelle zu streamen. Geben Sie dann beim zweiten Aufruf das Formatorc
an, umcustdata
in die Hive-ORC-Tabelle zu streamen.
Wenn die Standardausgabe im SSH-Terminal angehalten wird, was bedeutet, dass alle
custdata
gestreamt wurden, drücken Sie im SSH-Terminal <control-c>, um den Vorgang zu beenden.Hive-Tabellen in Cloud Storage auflisten
gcloud storage ls gs://BUCKET_NAME/tables/* --recursive
Hinweise:
- BUCKET_NAME: Geben Sie den Namen des Cloud Storage-Buckets ein, der Ihre Hive-Tabellen enthält (siehe Hive-Tabellen erstellen).
Führen Sie im SSH-Terminal auf dem Masterknoten Ihres Kafka-Clusters den folgenden
hive
-Befehl aus, um die gestreamten Kafka-custdata
-Nachrichten in den Hive-Tabellen in Cloud Storage zu zählen.hive -e "select count(1) from TABLE_NAME"
Hinweise:
- TABLE_NAME: Geben Sie entweder
cust_parquet
odercust_orc
als Namen der Hive-Tabelle an.
Erwarteter Auszug der Ausgabe:
- TABLE_NAME: Geben Sie entweder
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
- In the Google Cloud console, go to the Cloud Storage Buckets page.
- Click the checkbox for the bucket that you want to delete.
- To delete the bucket, click Delete, and then follow the instructions.
- So löschen Sie Ihren Kafka-Cluster:
gcloud dataproc clusters delete KAFKA_CLUSTER \ --region=${REGION}
Anleitungsschritte
Führen Sie die folgenden Schritte aus, um einen Dataproc-Kafka-Cluster zu erstellen, mit dem ein Kafka-Thema im Parquet- oder ORC-Format in Cloud Storage gelesen werden kann.
Kafka-Installationsskript in Cloud Storage kopieren
Das kafka.sh
-Skript für die Initialisierungsaktion installiert Kafka auf einem Dataproc-Cluster.
Dataproc-Kafka-Cluster erstellen
Kafka-Thema custdata
erstellen
So erstellen Sie ein Kafka-Thema im Dataproc-Kafka-Cluster:
Inhalte im Kafka-Thema custdata
veröffentlichen
Im folgenden Script wird das kafka-console-producer.sh
-Kafka-Tool verwendet, um fiktive Kundendaten im CSV-Format zu generieren.
Hive-Tabellen in Cloud Storage erstellen
Erstellen Sie Hive-Tabellen zum Empfangen von gestreamten Kafka-Themendaten.
Führen Sie die folgenden Schritte aus, um cust_parquet
- (Parquet) und cust_orc
- (ORC) Hive-Tabellen in Ihrem Cloud Storage-Bucket zu erstellen.
Kafka-Daten in Hive-Tabellen streamencustdata
Streamingdaten abfragen
...
Status: Running (Executing on YARN cluster with App id application_....)
----------------------------------------------------------------------------------------------
VERTICES MODE STATUS TOTAL COMPLETED RUNNING PENDING FAILED KILLED
----------------------------------------------------------------------------------------------
Map 1 .......... container SUCCEEDED 1 1 0 0 0 0
Reducer 2 ...... container SUCCEEDED 1 1 0 0 0 0
----------------------------------------------------------------------------------------------
VERTICES: 02/02 [==========================>>] 100% ELAPSED TIME: 9.89 s
----------------------------------------------------------------------------------------------
OK
10000
Time taken: 21.394 seconds, Fetched: 1 row(s)