Azure 事件中心 Python SDK

Azure Event Hub Python SDK

任何人都可以解释如何使用 python 事件中心 SDK 使用 "Event Hub-compatible name" 和 "Event Hub-Compatible endpoint"。 SDK 要求

# Address can be in either of these formats:
# "amqps://<URL-encoded-SAS-policy>:<URL-encoded-SAS- 
# "key>@<mynamespace>.servicebus.windows.net/myeventhub"
# "amqps://<mynamespace>.servicebus.windows.net/myeventhub"
ADDRESS = os.environ.get('EVENT_HUB_ADDRESS')

# SAS policy and key are not required if they are encoded in the URL
USER = os.environ.get('EVENT_HUB_SAS_POLICY')
KEY = os.environ.get('EVENT_HUB_SAS_KEY')

我需要帮助将默认端点下给出的字符串拟合到此示例中。

如果您想使用最新的 Azure Event Hub Python SDK 从 IoT Hub 内置端点接收设备到云的消息,还有另一种选择,您可以参考以下代码:

import os
import sys
import logging
import time
from azure.eventhub import EventHubClient, Receiver, Offset

PARTITION = "0"

total = 0
last_sn = -1
last_offset = "-1"

client = EventHubClient.from_iothub_connection_string("{iot hub connection string}", debug=True)

try:
    receiver = client.add_receiver("$default", PARTITION, operation='/messages/events')
    client.run()
    start_time = time.time()
    for event_data in receiver.receive(timeout=100):
        last_offset = event_data.offset
        last_sn = event_data.sequence_number
        print("Received: {}, {}".format(last_offset, last_sn))
        total += 1

    end_time = time.time()
    client.stop()
    run_time = end_time - start_time
    print("Received {} messages in {} seconds".format(total, run_time))

except KeyboardInterrupt:
    pass
finally:
    client.stop()

我觉得如果没有 特殊原因,最好使用 IoT Hub 自己的特定 Python 客户端库来接收消息。

鉴于您提到 "Event Hub-compatible name" 和 "Event Hub-Compatible endpoint",我假设您正在尝试连接到 IoT 中心的事件中心兼容端点。

有了这个 Event Hub 兼容名称iothub-ehub-getstarted-99999-xxxxxxxxxx 和这个 Event Hub 兼容端点Endpoint=sb://ihsuprodbyres999dednamespace.servicebus.windows.net/;SharedAccessKeyName=iothubowner;SharedAccessKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=

然后 EVENT_HUB_ADDRESS 看起来像这样:amqps://ihsuprodbyres999dednamespace.servicebus.windows.net/iothub-ehub-getstarted-99999-xxxxxxxxxx

对于 EVENT_HUB_SAS_POLICYEVENT_HUB_SAS_KEY 值,您可以使用 iothubownwer service 作为 SAS 策略及其对应的键。您可以在 IoT 中心 共享访问策略 页面的门户中找到这些内容。