简介:

使用Python SDK,基于EPH方式接收Azure Event Hub中存储的message,EventProcessorHost()中使用Azure Storage存储offerset等信息。目前版本的SDK对中国区的支持还不是太好,使用起来需要结合中国区的特点指定具体的endpoint。


示例程序:

import asyncio
from azure.eventprocessorhost import AbstractEventProcessor, EPHOptions
from azure.eventprocessorhost import AzureStorageCheckpointLeaseManager
from azure.eventprocessorhost import EventHubConfig
from azure.eventprocessorhost import EventProcessorHost
from azure.storage.blob import BlockBlobService class EventProcessor(AbstractEventProcessor): """
Example Implmentation of AbstractEventProcessor
"""
def __init__(self, params=None):
"""
Init Event processor
"""
self._msg_counter = 0
async def open_async(self, context):
"""
Called by processor host to initialize the event processor.
"""
print(context.partition_id) async def close_async(self, context, reason):
"""
Called by processor host to indicate that the event processor is being stopped.
(Params) Context:Information about the partition
""" print("Reason: " + reason)
print("context.partition_id: " + context.partition_id)
print("context.offset: " + context.offset)
print("context.sequence_number: {}".format(context.sequence_number)) async def process_events_async(self, context, messages):
"""
Called by the processor host when a batch of events has arrived.
This is where the real work of the event processor is done.
(Params) Context: Information about the partition, Messages: The events to be processed.
"""
print(context.partition_id)
print(messages)
print("-----")
await context.checkpoint_async() async def process_error_async(self, context, error):
"""
Called when the underlying client experiences an error while receiving.
EventProcessorHost will take care of recovering from the error and
continuing to pump messages,so no action is required from
(Params) Context: Information about the partition, Error: The error that occured.
"""
print(repr(error)) # 注意如果消息较多,请增加sleep的时间,防止程序提前终止
async def wait_and_close(host):
"""
Run EventProcessorHost for 6 minutes then shutdown.
"""
await asyncio.sleep(360)
await host.close_async() try: loop = asyncio.get_event_loop() # Storage Account Credentials
STORAGE_ACCOUNT_NAME = "yuvmtestdiag489"
STORAGE_KEY = "OgNFVB93P2oWCKcJaNOt4kuW0lf911D11v6NiHcDC6R0SdiqUJYlP8UdW7U4p0UzSnreII+7BnS9Cy1VsMSqGg=="
LEASE_CONTAINER_NAME = "leases5" # Eventhub config and storage manager
EH_CONFIG = EventHubConfig('cznamespace', 'yutaoeventhubtest', 'RootManageSharedAccessKey',
'wnwcU+VjKLGgNUwiecwAyHb9gAVPDIC+RvXu2JcDINc=', consumer_group="$default") # 注意务必对key进行urlencode编码
ADDRESS = ("amqps://"
"RootManageSharedAccessKey"
":"
"wnwcU%2bVjKLGgNUwiecwAyHb9gAVPDIC%211vXu2JcDINc%3d"
"@"
"cznamespace.servicebus.chinacloudapi.cn"
"/"
"yutaoeventhubtest") EH_CONFIG.client_address = ADDRESS
STORAGE_MANAGER = AzureStorageCheckpointLeaseManager(STORAGE_ACCOUNT_NAME,
STORAGE_KEY,
LEASE_CONTAINER_NAME,
storage_blob_prefix="blob.core.chinacloudapi.cn") eph_options = EPHOptions() #Event loop and host
LOOP = asyncio.get_event_loop()
HOST = EventProcessorHost(EventProcessor, EH_CONFIG, STORAGE_MANAGER, eph_options=eph_options,
ep_params=["param1", "param2"], loop=LOOP) # 重新设置一遍防止SDK擦除了之前的配置
STORAGE_MANAGER.storage_client = BlockBlobService(account_name=STORAGE_ACCOUNT_NAME,
account_key=STORAGE_KEY,
endpoint_suffix="core.chinacloudapi.cn") tasks = asyncio.gather(
HOST.open_async(),
wait_and_close(HOST)) loop.run_until_complete(tasks) except KeyboardInterrupt:
# Canceling pending tasks and stopping the loop
for task in asyncio.Task.all_tasks():
task.cancel()
loop.run_forever()
tasks.exception() finally:
loop.stop()

注意: 连接信息已经失效,仅供格式参考。

测试结果:

1
[<azure.eventhub.EventData object at 0x00000223AE556EF0>, <azure.eventhub.EventData object at 0x00000223AE556F98>, <azure.eventhub.EventData object at 0x00000223AE4DBA20>, <azure.eventhub.EventData object at 0x00000223AE4DB400>, <azure.eventhub.EventData object at 0x00000223AE4DBC88>, <azure.eventhub.EventData object at 0x00000223AE4DBAC8>, <azure.eventhub.EventData object at 0x00000223AE4FD7F0>, <azure.eventhub.EventData object at 0x00000223AE4FD6D8>, <azure.eventhub.EventData object at 0x00000223AE4FDBE0>, <azure.eventhub.EventData object at 0x00000223AE4FD048>]
-----
1
[<azure.eventhub.EventData object at 0x00000223AE4FD278>, <azure.eventhub.EventData object at 0x00000223AE4FDB70>, <azure.eventhub.EventData object at 0x00000223AE4FD668>, <azure.eventhub.EventData object at 0x00000223AE4FDAC8>, <azure.eventhub.EventData object at 0x00000223AE4FDB38>, <azure.eventhub.EventData object at 0x00000223AE4FDF60>, <azure.eventhub.EventData object at 0x00000223AE57AB38>, <azure.eventhub.EventData object at 0x00000223AE57A470>, <azure.eventhub.EventData object at 0x00000223AE57A748>]
-----
Reason: Shutdown
context.partition_id: 0
context.offset: 978600
context.sequence_number: 17559
Reason: Shutdown
context.partition_id: 1
context.offset: 978544
context.sequence_number: 17558 Process finished with exit code 0

参考示例:

azure-event-hubs-python/examples/eph.py

eph.py stop when the message not all received

EPH接收Event Hub Message的更多相关文章

  1. Azure Event Hub 技术研究系列3-Event Hub接收事件

    上篇博文中,我们通过编程的方式介绍了如何将事件消息发送到Azure Event Hub: Azure Event Hub 技术研究系列2-发送事件到Event Hub 本篇文章中,我们继续:从Even ...

  2. Event Hub小白入门指南

    Event Hub事件中心 本文的目的在于用最白的大白话,让你从“完全不懂”开始,理解什么是分布式大数据流平台Event Hub,并且理解它的关键概念,并且初步理解其收发数据API. 定义,Event ...

  3. 【Azure 事件中心】Azure Event Hub 新功能尝试 -- 异地灾难恢复 (Geo-Disaster Recovery)

    问题描述 关于Event Hub(事件中心)的灾备方案,大多数就是新建另外一个备用的Event Hub,当主Event Hub出现不可用的情况时,就需要切换到备Event Hub上. 而在切换的过程中 ...

  4. 【Azure 事件中心】 org.slf4j.Logger 收集 Event Hub SDK(Java) 输出日志并以文件形式保存

    问题描述 在使用Azure Event Hub的SDK时候,常规情况下,发现示例代码中并没有SDK内部的日志输出.因为在Java项目中,没有添加 SLF4J 依赖,已致于在启动时候有如下提示: SLF ...

  5. Azure Event Hub 技术研究系列2-发送事件到Event Hub

    上篇博文中,我们介绍了Azure Event Hub的一些基本概念和架构: Azure Event Hub 技术研究系列1-Event Hub入门篇 本篇文章中,我们继续深入研究,了解Azure Ev ...

  6. Azure IoT Hub和Event Hub相关的技术系列-索引篇

    Azure IoT Hub和Event Hub相关的技术系列,最近已经整理了不少了,统一做一个索引链接,置顶. Azure IoT 技术研究系列1-入门篇 Azure IoT 技术研究系列2-设备注册 ...

  7. Azure Event hub usage

    1. create event hub on azure watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/40 ...

  8. 【事件中心 Azure Event Hub】Event Hub Java SDK的消费端出现不消费某一个分区中数据的情况,出现IdleTimerExpired错误消息记录

    问题情形 使用Java SDK编写的Event Hub消费端应用,随机性遇见了某个分区没有消费消息的情况,在检查日志时候,有发现IdelTimeExpired的错误记录.在重启应用后,连接EventH ...

  9. 【事件中心 Azure Event Hub】关于EventHub中出现Error时候的一些问题(偶发错误,EventHub后台升级,用户端错误,Retry机制的重要性)

    请问对偶发的定义是多少频率? 针对偶发的定义,主要是看发生的时间非常短,次数极少(如 10次以内),并且发生的时候EventHub其他分区或其他连接都是正常接收和发送数据.所以对于频率是没有明确的定义 ...

随机推荐

  1. 静态页面表单中js验证

    笔记: 1. onblur事件:onblur 事件会在对象失去焦点时发生.http://www.w3school.com.cn/jsref/event_onblur.asp onkeyup事件:onk ...

  2. python 2 控制台传参,解包,编码问题初探

    python 2 控制台传参,需要从sys模块中导入argv,argv返回的第一个参数当前脚本(script)的文件名,后面是参数,参数个数必须和解包(unpack)时使用的参数个数一致 1.本例子演 ...

  3. 转 IntelliJ IDEA 快捷键

    https://www.cnblogs.com/clwydjgs/p/9390488.html 一.视图查看 Ctrl+F12 查看file,method结构图.类继承机构图 (不知道方法结构,Ctr ...

  4. [Contest20180323]King

    跳蚤国王要召开第二届内阁会议,所以把所有跳蚤都召集到了会议室.所有跳蚤在会议室的圆桌前坐成了一个圈,从$1$到$n$标号,每人的面前都有一盏明灯. 就在会议就要开始的时候,国王突然发现,并不是所有的灯 ...

  5. Problem G: 零起点学算法27——等级分制度

    #include<stdio.h> int main() { int a,b; while(scanf("%d %d",&a,&b)!=EOF) +a* ...

  6. SQL Server DBA 文章:116篇 --DBA_Huangzj

    http://blog.csdn.net/DBA_Huangzj/article/category/1133081

  7. Kubernetes环境下如何运行Coherence缓存集群

    Oracle官方出了一个如何在Docker环境下运行Coherence的技术文档,大家可以参考: https://github.com/oracle/docker-images/tree/master ...

  8. Python - 文本处理模块

    文本处理模块 本文地址: http://blog.csdn.net/caroline_wendy/article/details/27050431 Python的文本处理模块, 使用四种内置库. st ...

  9. Flask+uwsgi+Nginx环境搭建

    开源软件准备需要的软件列表:setuptools-33.1.1.zipPython-2.7.13.tgzpip-9.0.1.tar.gznginx-1.10.3.tar.gz软件统一上传到/usr/l ...

  10. pl/sql游标

    通过游标,我们可以取得返回结果集的任何一行记录,提高效率. 定义游标: type 游标名 is ref cursor 变量名 游标名 打开游标: open 游标变量 for select语句: 取出当 ...