Apache Kafka adalah platform streaming terdistribusi open source untuk pipeline data dan integrasi data real-time. Sistem ini menyediakan sistem streaming yang efisien dan skalabel untuk digunakan dalam berbagai aplikasi, termasuk:
- Analisis real-time
- Stream processing
- Agregasi log
- Pengiriman pesan terdistribusi
- Streaming acara
Tujuan
Instal Kafka di cluster HA Dataproc dengan ZooKeeper (disebut dalam tutorial ini sebagai "cluster Kafka Dataproc").
Buat data pelanggan fiktif, lalu publikasikan data ke topik Kafka.
Buat tabel Hive parquet dan ORC di Cloud Storage untuk menerima data topik Kafka yang di-streaming.
Kirimkan tugas PySpark untuk berlangganan dan melakukan streaming topik Kafka ke Cloud Storage dalam format Parquet dan ORC.
Jalankan kueri pada data tabel Hive yang di-streaming untuk menghitung pesan Kafka yang di-streaming.
Biaya
Dalam dokumen ini, Anda akan menggunakan komponen Google Cloudyang dapat ditagih berikut:
Untuk membuat perkiraan biaya berdasarkan proyeksi penggunaan Anda,
gunakan kalkulator harga.
Setelah menyelesaikan tugas yang dijelaskan dalam dokumen ini, Anda dapat menghindari penagihan berkelanjutan dengan menghapus resource yang Anda buat. Untuk mengetahui informasi selengkapnya, lihat Pembersihan.
Sebelum memulai
Jika Anda belum melakukannya, buat project Google Cloud .
- 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.
-
Verify 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.
-
Verify 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.
Telusuri kode.
Salin skrip tindakan inisialisasi
kafka.sh
ke bucket Cloud Storage Anda. Skrip ini menginstal Kafka pada cluster Dataproc.Buka Cloud Shell, lalu jalankan perintah berikut:
gcloud storage cp gs://goog-dataproc-initialization-actions-REGION/kafka/kafka.sh gs://BUCKET_NAME/scripts/
Lakukan penggantian berikut:
- REGION:
kafka.sh
disimpan di bucket yang diberi tag secara regional dan bersifat publik di Cloud Storage. Tentukan region Compute Engine yang secara geografis dekat, (contoh:us-central1
). - BUCKET_NAME: Nama bucket Cloud Storage Anda.
- REGION:
Buka Cloud Shell, lalu jalankan perintah
gcloud dataproc clusters create
berikut untuk membuat cluster HA cluster Dataproc yang menginstal komponen Kafka dan ZooKeeper: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
Catatan:
- KAFKA_CLUSTER: Nama cluster, yang harus unik dalam project. Nama harus diawali dengan huruf kecil, dan dapat berisi hingga 51 huruf kecil, angka, dan tanda hubung. Tidak boleh diakhiri dengan tanda hubung. Nama cluster yang dihapus dapat digunakan kembali.
- PROJECT_ID: Project yang akan dikaitkan dengan cluster ini.
- REGION: Region Compute Engine tempat cluster akan berada, seperti
us-central1
.- Anda dapat menambahkan tanda
--zone=ZONE
opsional untuk menentukan zona dalam region yang ditentukan, sepertius-central1-a
. Jika Anda tidak menentukan zona, fitur penempatan autozone Dataproc akan memilih zona dengan region yang ditentukan.
- Anda dapat menambahkan tanda
--image-version
: Versi image Dataproc2.1-debian11
direkomendasikan untuk tutorial ini. Catatan: Setiap versi image berisi serangkaian komponen yang telah diinstal sebelumnya, termasuk komponen Hive yang digunakan dalam tutorial ini (lihat Versi image Dataproc yang didukung).--num-master
:3
node master membuat cluster HA. Komponen Zookeeper, yang diperlukan oleh Kafka, telah diinstal sebelumnya di cluster HA.--enable-component-gateway
: Mengaktifkan Gateway Komponen Dataproc.- BUCKET_NAME: Nama bucket Cloud Storage Anda yang berisi skrip inisialisasi
/scripts/kafka.sh
(lihat Menyalin skrip penginstalan Kafka ke Cloud Storage).
Gunakan utilitas SSH untuk membuka jendela terminal di VM master cluster.
Buat topik
custdata
Kafka./usr/lib/kafka/bin/kafka-topics.sh \ --bootstrap-server KAFKA_CLUSTER-w-0:9092 \ --create --topic custdata
Catatan:
KAFKA_CLUSTER: Masukkan nama cluster Kafka Anda.
-w-0:9092
menandakan broker Kafka yang berjalan di port9092
pada nodeworker-0
.Anda dapat menjalankan perintah berikut setelah membuat topik
custdata
:# 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
Salin, lalu tempel skrip di terminal SSH pada node master cluster Kafka Anda. Tekan <return> untuk menjalankan skrip.
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=:"
Catatan:
- KAFKA_CLUSTER: Nama cluster Kafka Anda.
Jalankan perintah Kafka berikut untuk mengonfirmasi bahwa topik
custdata
berisi 10.000 pesan./usr/lib/kafka/bin/kafka-run-class.sh kafka.tools.GetOffsetShell \ --broker-list KAFKA_CLUSTER-w-0:9092 \ --topic custdata
Catatan:
- KAFKA_CLUSTER: Nama cluster Kafka Anda.
Output yang diharapkan:
custdata:0:10000
Masukkan BUCKET_NAME Anda dalam skrip berikut, lalu salin dan tempel skrip ke terminal SSH di node master cluster Kafka Anda, lalu tekan <return> untuk membuat skrip
~/hivetables.hql
(Hive Query Language).Anda akan menjalankan skrip
~/hivetables.hql
pada langkah berikutnya untuk membuat tabel Hive Parquet dan ORC di bucket Cloud Storage Anda.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
Di terminal SSH pada node master cluster Kafka Anda, kirimkan tugas Hive
~/hivetables.hql
untuk membuat tabel Hivecust_parquet
(parquet) dancust_orc
(ORC) di bucket Cloud Storage Anda.gcloud dataproc jobs submit hive \ --cluster=KAFKA_CLUSTER \ --region=REGION \ -f ~/hivetables.hql
Catatan:
- Komponen Hive sudah diinstal sebelumnya di cluster Kafka Dataproc. Lihat versi rilis 2.1.x untuk mengetahui daftar versi komponen Hive yang disertakan dalam image 2.1 yang baru dirilis.
- KAFKA_CLUSTER: Nama cluster Kafka Anda.
- REGION: Region tempat cluster Kafka Anda berada.
- Jalankan perintah berikut di terminal SSH pada node master cluster Kafka Anda untuk menginstal library
kafka-python
. Klien Kafka diperlukan untuk melakukan streaming data topik Kafka ke Cloud Storage.
pip install kafka-python
Masukkan BUCKET_NAME Anda, lalu salin dan tempel kode PySpark berikut ke terminal SSH di node master cluster Kafka Anda, lalu tekan <return> untuk membuat file
streamdata.py
.Skrip ini akan berlangganan topik Kafka
custdata
, lalu melakukan streaming data ke tabel Hive Anda di Cloud Storage. Format output, yang dapat berupa parquet atau ORC, diteruskan ke skrip sebagai parameter.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
Di terminal SSH pada node master cluster Kafka, jalankan
spark-submit
untuk melakukan streaming data ke tabel Hive di Cloud Storage.Masukkan nama KAFKA_CLUSTER dan output FORMAT, lalu salin dan tempel kode berikut ke terminal SSH di node master cluster Kafka Anda, lalu tekan <return> untuk menjalankan kode dan mengalirkan data
custdata
Kafka dalam format parquet ke tabel Hive Anda di Cloud Storage.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
Catatan:
- KAFKA_CLUSTER: Masukkan nama cluster Kafka Anda.
- FORMAT: Tentukan
parquet
atauorc
sebagai format output. Anda dapat menjalankan perintah secara berturut-turut untuk melakukan streaming kedua format ke tabel Hive: misalnya, pada pemanggilan pertama, tentukanparquet
untuk melakukan streaming topik Kafkacustdata
ke tabel parquet Hive; lalu, pada pemanggilan kedua, tentukan formatorc
untuk melakukan streamingcustdata
ke tabel ORC Hive.
Setelah output standar berhenti di terminal SSH, yang menandakan bahwa semua
custdata
telah di-streaming, tekan <control-c> di terminal SSH untuk menghentikan proses.Mencantumkan tabel Hive di Cloud Storage.
gcloud storage ls gs://BUCKET_NAME/tables/* --recursive
Catatan:
- BUCKET_NAME: Masukkan nama bucket Cloud Storage yang berisi tabel Hive Anda (lihat Membuat tabel Hive).
Di terminal SSH pada node master cluster Kafka, jalankan perintah
hive
berikut untuk menghitung pesan Kafkacustdata
yang di-streaming dalam tabel Hive di Cloud Storage.hive -e "select count(1) from TABLE_NAME"
Catatan:
- TABLE_NAME: Tentukan
cust_parquet
ataucust_orc
sebagai nama tabel Hive.
Cuplikan output yang diharapkan:
- TABLE_NAME: Tentukan
- 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.
- Hapus cluster Kafka Anda:
gcloud dataproc clusters delete KAFKA_CLUSTER \ --region=${REGION}
Langkah-langkah tutorial
Lakukan langkah-langkah berikut untuk membuat cluster Kafka Dataproc guna membaca topik Kafka ke Cloud Storage dalam format parquet ATAU ORC.
Menyalin skrip penginstalan Kafka ke Cloud Storage
Skrip kafka.sh
tindakan inisialisasi
ini menginstal Kafka pada cluster Dataproc.
Membuat cluster Kafka Dataproc
Membuat topik Kafka custdata
Untuk membuat topik Kafka di cluster Kafka Dataproc:
Memublikasikan konten ke topik Kafka custdata
Skrip berikut menggunakan alat Kafka kafka-console-producer.sh
untuk
membuat data pelanggan fiktif dalam format CSV.
Membuat tabel Hive di Cloud Storage
Buat tabel Hive untuk menerima data topik Kafka yang di-streaming.
Lakukan langkah-langkah berikut untuk membuat tabel Hive cust_parquet
(parquet) dan
cust_orc
(ORC) di bucket Cloud Storage Anda.
Streaming Kafka custdata
ke tabel Hive
Mengkueri data yang di-streaming
...
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)