【问题标题】:How to pull GCP Pub/Sub messages with a python HTTP server?如何使用 python HTTP 服务器提取 GCP Pub/Sub 消息?
【发布时间】:2021-08-20 05:56:42
【问题描述】:

GCP 为 Pub/Sub 提供 REST API:https://cloud.google.com/pubsub/docs/reference/rest

Python API 允许用户如下拉取消息,使用 Python 库https://googleapis.dev/python/pubsub/latest/index.html

import os
from google.cloud import pubsub_v1

topic_name = 'projects/{project_id}/topics/{topic}'.format(
    project_id=os.getenv('GOOGLE_CLOUD_PROJECT'),
    topic='MY_TOPIC_NAME',  # Set this to something appropriate.
)

subscription_name = 'projects/{project_id}/subscriptions/{sub}'.format(
    project_id=os.getenv('GOOGLE_CLOUD_PROJECT'),
    sub='MY_SUBSCRIPTION_NAME',  # Set this to something appropriate.
)

def callback(message):
    print(message.data)
    message.ack()

with pubsub_v1.SubscriberClient() as subscriber:
    subscriber.create_subscription(
        name=subscription_name, topic=topic_name)
    future = subscriber.subscribe(subscription_name, callback)
    try:
        future.result()
    except KeyboardInterrupt:
        future.cancel()

但是用户必须使用这个库吗?

我想使用不同的 HTTP 客户端通过使用 Pub/Sub API 的 GET 请求来解析这些消息。原则上,这应该通过 requests 库之类的东西来完成,使用 get 方法:

import requests

x = requests.get(END_POINT)
print(x.status_code)

但是,这是否适用于来自 Google Pub/Sub 的流式 GET 请求?

【问题讨论】:

    标签: python http get client google-cloud-pubsub


    【解决方案1】:

    这不是 GET,而是一个帖子,是的,您可以使用 API 来拉取消息。你有文档here

    不要忘记ack消息或修改AckDeadline

    Google Cloud 中的一切都是 API,但这些库可以帮助您轻松执行任务。但如果你更喜欢重新发明轮子,何乐而不为!

    【讨论】:

    • 感谢您的回答。我对两件事感到困惑:(1)如何对 POST 请求进行“响应”?我错过了什么吗? (2) 我首先在 Python 中对此进行调查,因为我需要用一种没有客户端库的语言编写 PubSub 订阅,即 R
    • 谢谢,我想我一直很困惑如何处理 POST 请求的“响应”。
    猜你喜欢
    • 2021-10-02
    • 2021-11-14
    • 2019-04-10
    • 2021-10-09
    • 1970-01-01
    • 2021-06-20
    • 2021-11-08
    • 2020-02-05
    • 2021-04-26
    相关资源
    最近更新 更多