简体   繁体   English

带有python的Google Pubsub模拟器

[英]Google Pubsub emulator with python

Does anyone have a very basic pub/sub example for Python that uses the emulator. 是否有人有使用该模拟器的Python基本发布/订阅示例。

This here is my subscriber code 这是我的订户代码

## setup subscribers
from google.cloud import pubsub

print("subscribing to topic")


subscriber = pubsub.SubscriberClient()
subscription_path = subscriber.subscription_path(app.config['PUB_SUB_PROJECT'], app.config['PUB_SUB_TOPIC'])

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


subscriber.subscribe(subscription_path, callback=callback)

And then here is my code for publishing 然后这是我的发布代码

from google.cloud import pubsub
publisher = pubsub.PublisherClient()
topic_path = publisher.topic_path(app.config['PUB_SUB_PROJECT'], app.config['PUB_SUB_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)
print("published topic")

It seems that publishing works -> but I think it's actually publishing to the cloud queue and not to the emulator. 似乎发布有效->但我认为它实际上是发布到云队列而不是模拟器。 Therefor my subscriber never receives anything. 因此,我的订户从未收到任何东西。

Any tipps and tricks are welcome. 欢迎任何小费和技巧。 I believe it's as simple as ensuring that the publisher publishes to the emulator and the subscriber reads from the emulator. 我相信这就像确保发布者将发布到仿真器以及订阅者从仿真器中读取一样简单。

In Python you don't need to make any code changes to use the emulator. 在Python中,您无需进行任何代码更改即可使用模拟器。 Instead, you must have the PUBSUB_EMULATOR_HOST and PUBSUB_PROJECT_ID environmental variables defined. 而是必须定义PUBSUB_EMULATOR_HOSTPUBSUB_PROJECT_ID环境变量。

The easiest way to set them is to run $(gcloud beta emulators pubsub env-init) before starting your program. 设置它们的最简单方法是在启动程序之前运行$(gcloud beta emulators pubsub env-init) if you are using Google App Engine locally, run that command and then start your app with dev_appserver.py app.yaml --env_var PUBSUB_EMULATOR_HOST=${PUBSUB_EMULATOR_HOST} . 如果您在本地使用Google App Engine,请运行该命令,然后使用dev_appserver.py app.yaml --env_var PUBSUB_EMULATOR_HOST=${PUBSUB_EMULATOR_HOST}启动应用。

This is documented at https://cloud.google.com/pubsub/docs/emulator https://cloud.google.com/pubsub/docs/emulator中有记录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM