Google Cloud Pub/Sub – Basic Example mit Python


Ein Reminder für mich und vielleicht hilft es noch jemand anderem. Damit das ganze lokal getestet werden kann muss der pubsub emulator installiert werden:

gcloud beta emulators pubsub start

# Um dem Programm zu sagen, dass es auf den Emulator geht folgende Zeilen in jedem Terminal ausführen:

set PUBSUB_PROJECT_ID=rapnika-cluster
set PUBSUB_EMULATOR_HOST=localhost:8085

Publish

from google.cloud import pubsub
project           = "rapnika-cluster"
subscription_topic = "zwn-processor"

publisher = pubsub.PublisherClient()
topic_path = publisher.topic_path(project, subscription_topic)

try:
    topic = publisher.create_topic(topic_path)
except Exception:
    app.logger.info("Topic already exists")
data = "ein test"
data = data.encode('utf-8')
publisher.publish(topic_path, data=data)

Subscribe

project           = "rapnika-cluster"
subscription_name = "subscription-test"
subscription_topic = "zwn-processor"


subscriber = pubsub_v1.SubscriberClient()
topic_path = subscriber.topic_path(project, subscription_topic)
subscription_path = subscriber.subscription_path(project, subscription_name)

try:
    subscription = subscriber.create_subscription(subscription_path, topic_path)
    print('Subscription created: {}'.format(subscription))
except:
    app.logger.info("subscriptions already exists")


def callback(message):
    print('Received message: {}'.format(message))
    message.ack()

subscriber.subscribe(subscription_path, callback=callback)

Weiterführende Links

Die folgenden Links könnten nützlich sein:

  • https://cloud.google.com/pubsub/docs/pull
  • https://cloud.google.com/pubsub/docs/publisher
  • https://cloud.google.com/pubsub/docs/admin
  • https://cloud.google.com/pubsub/docs/emulator