【问题标题】:Python - Streaming data from file to asyncio-enabled Kinesis ProducerPython - 将数据从文件流式传输到启用异步的 Kinesis Producer
【发布时间】:2019-03-13 19:51:10
【问题描述】:

我正在使用 Python 3.6 中启用异步的 Kinesis Producer 模块,以部署到 AWS Lambda(因此我需要它与 3.6 兼容)。

我的用例是从磁盘延迟读取文件(大约 100MB 压缩 - 1GB 未压缩)并将数据(一次 500 行)流式传输到 Kinesis Producer。我希望 Kinesis Producer 在我读取下一批 500 行时开始将 500 条记录推送到 Kinesis。

我注意到的是,它一次读取整个文件 500 行,然后开始将数据推送到 Kinesis Producer。原因似乎是因为我没有打电话给await asyncio.sleep(1),但我也不知道我这样做是否正确。

def lambda_handler(event, context):
    event_loop = asyncio.get_event_loop()
    # Extract filename from event and download file from S3
    event_loop.run_until_complete(process(filename))
    pending = asyncio.Task.all_tasks()
    event_loop.run_until_complete(asyncio.gather(*pending))


async def process(filename):
    for chunk in read_lines(filename, MAX_RECORDS_IN_BATCH):
    asyncio.ensure_future(write_kinesis(chunk)).add_done_callback(callback)


def callback(result):
    print(str(result))


async def write_kinesis(records):
    future = asyncio.ensure_future(producer.put_records(records=records))

如果我将await asyncio.sleep(.1) 添加到process(filename) 函数的末尾,它似乎完全符合我的要求,当然,它实际上会阻塞主线程0.1 秒。

Q- 使用 asyncio.sleep 阻塞足够长的时间让 Kinesis Producer 将数据推送出去,这就是诀窍吗?它睡得越少,我在内存中保存的数据就越多,因为 kinesis 客户端没有太多时间将数据推出,但它会运行得更快(在一定程度上)?

Q- 我这样做是否正确?同样,我尝试读取 500 行,推送到 kinesis(异步),在 Kinesis 客户端工作时再读取 500 行,冲洗并重复。

另外,当从回调函数中查看打印语句时,我注意到如果 write_kinesis 函数没有返回任何内容,则回调的 print 语句有result=None,而如果 write_kinesis 函数返回 Future,则回调的 print 语句有result=<Task pending...11b35f18>()

Q-我假设没有return语句没有结果,但是为什么在状态仍然是“Pending”时调用回调函数?

编辑 1:我忘了说,Kinesis 客户端已经启用了异步功能。

【问题讨论】:

  • 问题到底是什么?我会编辑它,但如果你澄清一下可能会更好:-)
  • 是的,对不起......他们被埋在大量的文字中。查看更改,谢谢!

标签: python python-3.x python-asyncio


【解决方案1】:

你只需用 await 调用异步函数

async def process(filename):
    for chunk in read_lines(filename, MAX_RECORDS_IN_BATCH):
        await producer.put_records(records=chunk)

async def run():
    # Extract filename from event and download file from S3
    await process(filename)

loop = asyncio.get_event_loop()
loop.run_until_complete( run() )
loop.close()

【讨论】:

  • read_lines 可能在这里同步 - aiofiles 对文件 OP 进行异步读取
  • 嗯...我不知道为什么我第一次(以为我)尝试这种方式时它不起作用,但只是等待生产者调用确实有效。也就是说,出于某种我不知道的原因,它大约是在 asyncio.ensure_future 中包装生产者调用并在其后加上 await asyncio.sleep(.05) 的一半。但是,这超出了这个特定问题的范围......
  • 有趣。您不必等待 read_lines 中的每个块。你可以只做 temp_list.append(producer.put_records()) 然后 asyncio.gather 等待所有的块,然后把它们全部踢掉。
猜你喜欢
  • 2018-08-10
  • 2018-12-05
  • 2016-12-24
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-07
相关资源
最近更新 更多