unisbadri.com » Python Java Golang Typescript Kotlin Ruby Rust Dart PHP
Google Pub/Sub

Google Pub/Sub #

Google Cloud Pub/Sub adalah layanan pesan yang memungkinkan aplikasi mengirim dan menerima pesan dari berbagai komponen yang terdistribusi. Ini membantu dalam membangun sistem yang terdesentralisasi dan dapat diskalakan dengan mudah.

1. Persiapan Awal #

Mengaktifkan Google Cloud Pub/Sub API #

  1. Buka Google Cloud Console.
  2. Pilih atau buat proyek baru.
  3. Aktifkan Google Cloud Pub/Sub API untuk proyek Anda.

Menginstal Google Cloud SDK #

Jika belum terinstal, instal Google Cloud SDK untuk mengelola proyek dan kredensial:

curl -O https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-sdk-350.0.0-linux-x86_64.tar.gz
tar -xf google-cloud-sdk-350.0.0-linux-x86_64.tar.gz
./google-cloud-sdk/install.sh
./google-cloud-sdk/bin/gcloud init

Menginstal Library Python #

Instal library google-cloud-pubsub menggunakan pip:

pip install google-cloud-pubsub

2. Menghubungkan ke Google Cloud Pub/Sub dan Operasi Dasar #

Mengatur Kredensial #

Konfigurasikan kredensial untuk proyek Anda. Anda bisa mengatur variabel lingkungan GOOGLE_APPLICATION_CREDENTIALS dengan jalur ke file kunci JSON dari akun layanan yang memiliki izin yang diperlukan.

export GOOGLE_APPLICATION_CREDENTIALS="path/to/your-service-account-file.json"

Membuat Publisher dan Subscriber #

Berikut adalah contoh bagaimana membuat Publisher dan Subscriber menggunakan library google-cloud-pubsub:

from google.cloud import pubsub_v1

# Menginisialisasi Publisher
publisher = pubsub_v1.PublisherClient()
project_id = 'your-project-id'
topic_id = 'my-topic'
topic_path = publisher.topic_path(project_id, topic_id)

# Membuat Topic jika belum ada
try:
    topic = publisher.create_topic(request={"name": topic_path})
    print(f"Topic created: {topic.name}")
except Exception as e:
    print(f"Topic already exists: {e}")

# Mengirim pesan ke topic
def publish_message(data):
    future = publisher.publish(topic_path, data.encode('utf-8'))
    print(f"Published message ID: {future.result()}")

publish_message('Hello, World!')

# Menginisialisasi Subscriber
subscriber = pubsub_v1.SubscriberClient()
subscription_id = 'my-subscription'
subscription_path = subscriber.subscription_path(project_id, subscription_id)

# Membuat Subscription jika belum ada
try:
    subscription = subscriber.create_subscription(request={"name": subscription_path, "topic": topic_path})
    print(f"Subscription created: {subscription.name}")
except Exception as e:
    print(f"Subscription already exists: {e}")

# Fungsi untuk menerima pesan
def callback(message):
    print(f"Received message: {message.data.decode('utf-8')}")
    message.ack()

# Menerima pesan dari subscription
streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback)
print(f"Listening for messages on {subscription_path}..\n")

# Untuk menjaga script tetap berjalan agar dapat menerima pesan
import time
try:
    while True:
        time.sleep(60)
except KeyboardInterrupt:
    streaming_pull_future.cancel()

3. Operasi Lanjutan #

Google Cloud Pub/Sub mendukung berbagai operasi lanjutan seperti pengaturan atribut pesan, penanganan pesan yang gagal, dan lainnya.

Mengatur Atribut Pesan #

def publish_message_with_attributes(data, attributes):
    future = publisher.publish(topic_path, data.encode('utf-8'), **attributes)
    print(f"Published message ID: {future.result()}")

attributes = {'attribute1': 'value1', 'attribute2': 'value2'}
publish_message_with_attributes('Hello with attributes!', attributes)

Penanganan Pesan yang Gagal #

Anda bisa mengatur subscriber untuk mengatur jumlah maksimum pengulangan pesan yang gagal dan waktu tunggu antar pengulangan.

from google.cloud.pubsub_v1.types import RetryPolicy

retry_policy = RetryPolicy(
    minimum_backoff=10,  # Minimum waktu tunggu antara pengulangan (dalam detik)
    maximum_backoff=600  # Maksimum waktu tunggu antara pengulangan (dalam detik)
)

subscription = subscriber.create_subscription(
    request={
        "name": subscription_path,
        "topic": topic_path,
        "retry_policy": retry_policy
    }
)

Kesimpulan #

Google Cloud Pub/Sub adalah layanan pesan yang kuat dan fleksibel yang mendukung komunikasi asinkron antara komponen aplikasi yang terdistribusi. Dengan library google-cloud-pubsub, integrasi dengan aplikasi Python menjadi mudah dan efisien. Untuk informasi lebih lanjut, Anda bisa merujuk ke dokumentasi resmi Google Cloud Pub/Sub.