如何使用PublisherServiceAsyncClient

问题描述 投票:0回答:1

我正在尝试使用 pubsublite 中的 AsyncPublisherClient

pip install google-cloud-pubsublite==1.8.3
from google.cloud import pubsublite_v1

pubsub = pubsublite_v1.AsyncPublisherClient()

错误:模块没有属性“AsyncPublisherClient”

文档非常稀缺,我什至在 virtualenv 目录中找不到这个类,只是它的接口。

如何使用这个库?

编辑:看起来正确的班级是

PublisherServiceAsyncClient


编辑2:

from google.cloud.pubsublite_v1.types.publisher import PublishRequest
from google.cloud.pubsublite_v1.types import PubSubMessage
from google.cloud.pubsublite_v1 import PublisherServiceAsyncClient

pubsub = PublisherServiceAsyncClient()

message = PubSubMessage(data=json.dumps(payload).encode("utf-8"))

request = PublishRequest(topic=os.environ["TOPIC"], messages=[message])

async def request_generator():
    yield request

await pubsub.publish(requests=request_generator())

ValueError:PublishRequest 的未知字段:主题

python google-cloud-platform google-cloud-pubsub
1个回答
0
投票

PublishRequest
对象的使用可能会出现问题:在Pub/Sub Lite中,topic不是直接在
PublishRequest
中指定的。相反,主题通常是客户端配置的一部分。

所以在创建

PublisherServiceAsyncClient
实例时需要指定主题。
创建
PublishRequest
而不指定主题:
PublishRequest
只需要发布消息。

from google.cloud.pubsublite_v1 import PublisherServiceAsyncClient, PublisherOptions
from google.cloud.pubsublite_v1.types import PubSubMessage, PublishRequest
import os
import json

# Configure the topic information
topic_path = f"projects/{os.environ['PROJECT_NUMBER']}/locations/{os.environ['CLOUD_REGION']}/topics/{os.environ['TOPIC_ID']}"

# Initialize the client with the topic
client_options = PublisherOptions(topic_path=topic_path)
pubsub = PublisherServiceAsyncClient(client_options=client_options)

# Prepare your message
message = PubSubMessage(data=json.dumps(payload).encode("utf-8"))

# Create a PublishRequest without specifying the topic
request = PublishRequest(messages=[message])

async def request_generator():
    yield request

# Publish the message
await pubsub.publish(requests=request_generator())

PublisherOptions
用于为客户端配置主题信息。

© www.soinside.com 2019 - 2024. All rights reserved.