简体   繁体   English

如何将事件从文件发送到事件中心

[英]How to send events from file to event hub

I am new to EventHub and using Python scripts to send events one by one to Eventhub in my project.我是 EventHub 的新手,在我的项目中使用 Python 脚本将事件一个一个发送到 EventHub。 Is it possible to keep all the events in a file and send all of them together to EventHub?是否可以将所有事件保存在一个文件中并将所有事件一起发送到 EventHub?

What I am trying to achieve is that: Sending thousands of events to EventHub per second.我想要实现的是:每秒向 EventHub 发送数千个事件。 So I can keep all the thousand events/messages in one file and send them in single go.所以我可以将所有一千个事件/消息保存在一个文件中,并一次性发送它们。

Please suggest ways to achieve this.请提出实现这一目标的方法。

Here is the code which you can use to send events in batch这是您可以用来批量发送事件的代码

 #!/usr/bin/env python """ An example to show batch sending events to an Event Hub. """ # pylint: disable=C0111 import sys import logging import datetime import time import os from azure.eventhub import EventHubClient, Sender, EventData import examples logger = examples.get_logger(logging.INFO) # 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') def data_generator(): for i in range(1500): logger.info("Yielding message {}".format(i)) yield b"Hello world" try: if not ADDRESS: raise ValueError("No EventHubs URL supplied.") client = EventHubClient(ADDRESS, debug=False, username=USER, password=KEY) sender = client.add_sender(partition="1") client.run() try: start_time = time.time() data = EventData(batch=data_generator()) sender.send(data) except: raise finally: end_time = time.time() client.stop() run_time = end_time - start_time logger.info("Runtime: {} seconds".format(run_time)) except KeyboardInterrupt: pass

Hope it helps.希望能帮助到你。

For the latest version (5.2.0) of the library ( GitHub , Reference docs , you could send events by batches and set the body and properties like this:对于库的最新版本(5.2.0)( GitHubReference docs ,您可以批量发送事件并设置主体和属性,如下所示:

from azure.eventhub import EventHubProducerClient, EventHubConsumerClient, EventData
import json

connection_str = '<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>'
eventhub_name = '<< NAME OF THE EVENT HUB >>'
client = EventHubProducerClient.from_connection_string(connection_str, eventhub_name=eventhub_name)

event_data_batch = client.create_batch()
can_add = True
while can_add:
    try:
        content = json.dumps({"LocationId": "123", "userId": "123"})
        event_data = EventData(body = content) # body can be of type `str` or `bytes`
        event_data.properties = {"Type": "iPhone"}
        event_data_batch.add(event_data)
    except ValueError:
        can_add = False  # EventDataBatch object reaches max_size.

with client:
    client.send_batch(event_data_batch)

To consume the events:消费事件:

consumer_group = "$Default"
client = EventHubConsumerClient.from_connection_string(
        connection_str, consumer_group, eventhub_name=eventhub_name
    )
def on_event_batch(partition_context, events):
    partition_context.update_checkpoint()
    for e in events:
        print(e.body_as_str())
        print("properties={}".format(e.properties))

with client:
    client.receive_batch(
        on_event_batch=on_event_batch,
        starting_position="-1",  # "-1" is from the beginning of the partition.
    )
    # receive events from specified partition:
    # client.receive(on_event=on_event, partition_id='0')

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

相关问题 使用 Python 将事件发送到 Azure 事件中心 - Send events to Azure event hub using Python 尝试从 python 中的 azure 数据块中的事件中心读取事件 - Trying to read events from event hub in azure databricks in python 如何持续从证券交易所等网站获取数据并使用 python 将其发送到 azure 事件中心? - How to continuously fetch data from websites like Stock exchange and send it to azure event hub using python? 如何在Python中使用amqp将消息发送到Azure事件中心 - How to send message to Azure event hub with amqp in python 如何将数据发送到事件中心并安排其每10秒运行一次? - How send data to the event hub and schedule it to run for every 10 seconds? 在 python azure 事件中心消费事件 - consume events in python azure event hub 将 XML 文件内容发送到事件中心并从 Databricks 中读取 - Sending XML file content to Event Hub and read it from Databricks 如何从 avro 文件转换为 json 文件,该文件最初作为原始 json 通过 Postman 到 Z3A580F14C3022038F63F51 发送 - How to convert from an avro file to a json file, which was originally sent as raw json via Postman through Azure Event Hub? 事件中心中具有不同分区键的事件批次 - Batch of events having different partition key in event hub 将 JSON 文件发送到 Azure 事件中心 - Sending JSON File to Azure Event Hub
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM