利用 asyncio.queue 构建削峰填谷的高性能异步管道,核心做法是启动固定数量的消费者协程(worker)持续从队列中拉取任务并处理,而生产者只需将任务放入队列即可。通过设置队列的 maxsize 参数,当队列满时生产者会自动阻塞等待,从而在内存层面实现流量整形,防止后端服务因瞬时高并发请求而过载。

如何配置队列大小以控制内存占用
要控制内存占用,必须为 asyncio.Queue 指定 maxsize 参数。如果不指定,队列默认无上限,生产者会无限快地向内存中塞入数据,导致内存溢出。设置 maxsize 后,队列会在达到容量时自动暂停生产者的 put 操作,直到消费者腾出空间。

import asyncio
import time
# 定义最大队列深度,例如限制为 5 个任务
QUEUE_MAX_SIZE = 5
processed_count = 0
async def producer(queue, task_id):
global processed_count
# 模拟生成任务
task = f"Task-{task_id}"
print(f"Producer: Putting {task}")
await queue.put(task) # 如果队列满,这里会挂起
print(f"Producer: {task} put successfully")
async def consumer(queue, worker_id):
global processed_count
while True:
try:
# 获取任务,如果队列为空则挂起
task = await queue.get()
print(f"Worker-{worker_id}: Processing {task}")
# 模拟耗时处理
await asyncio.sleep(1)
print(f"Worker-{worker_id}: Finished {task}")
queue.task_done()
processed_count += 1
except asyncio.CancelledError:
break
async def main():
# 创建有界队列
q = asyncio.Queue(maxsize=QUEUE_MAX_SIZE)
# 启动 2 个消费者
consumers = [asyncio.create_task(consumer(q, i)) for i in range(2)]
# 启动 10 个生产者任务
producers = [asyncio.create_task(producer(q, i)) for i in range(10)]
# 等待所有生产者完成
await asyncio.gather(*producers)
# 等待队列清空
await q.join()
# 取消消费者
for c in consumers:
c.cancel()
print(f"Total processed: {processed_count}")
asyncio.run(main())
运行上述代码,你会观察到生产者并非一次性全部打印“put successfully”,而是分批次进行。当队列中有 5 个任务时,第 6 个生产者会等待,直到某个消费者处理完一个任务并调用 task_done() 后,队列腾出位置,被阻塞的生产者才会继续执行。这种机制确保了内存中同时存在的任务数不会超过 maxsize 设定的阈值。
如何实现优雅关闭与任务确认
在异步管道中,确保所有任务都被处理且程序能安全退出,关键在于正确使用 queue.join() 和 task_done()。生产者每放入一个任务,队列内部的未完成任务计数器加一;消费者每处理完一个任务,必须调用 task_done() 使计数器减一。当计数器归零时,queue.join() 返回,表明所有已提交的任务均已处理完毕。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。

import asyncio
import signal
running = True
async def graceful_shutdown(queue, workers):
global running
loop = asyncio.get_event_loop()
def stop_handler():
global running
running = False
# 唤醒所有可能阻塞在 get() 上的消费者
for w in workers:
if not w.done():
w.cancel()
# 注册信号处理器
loop.add_signal_handler(signal.SIGINT, stop_handler)
loop.add_signal_handler(signal.SIGTERM, stop_handler)
# 等待队列清空
await queue.join()
print("All tasks completed.")
async def worker(queue, worker_id):
while running:
try:
task = await asyncio.wait_for(queue.get(), timeout=1.0)
print(f"Worker-{worker_id} processing {task}")
await asyncio.sleep(0.5) # Simulate work
queue.task_done()
except asyncio.TimeoutError:
continue
except asyncio.CancelledError:
break
async def main():
q = asyncio.Queue()
workers = [asyncio.create_task(worker(q, i)) for i in range(3)]
# 模拟一些任务
for i in range(5):
await q.put(f"Data-{i}")
await asyncio.sleep(0.2)
await graceful_shutdown(q, workers)
asyncio.run(main())
在实际应用中,如果需要在收到中断信号时停止服务,不能简单地杀死进程,否则正在处理的数据可能会丢失。通过维护一个全局状态标志 running,并在信号处理函数中将其设为 False,配合 asyncio.wait_for 的超时机制,消费者可以定期检查是否应该退出。当主逻辑认为所有任务已完成(如 queue.join() 返回)或收到终止信号时,取消所有 Worker 协程,从而实现平滑关闭。这种模式保证了即使在高负载下,系统也能有序地释放资源,避免僵尸进程或数据不一致问题。
当队列满时生产者行为的具体表现是什么
当 asyncio.Queue 达到 maxsize 上限时,调用 await queue.put(item) 的生产者协程会被挂起(Suspend),进入事件循环的等待队列中,不再消耗 CPU 时间片。此时,该生产者协程的状态变为“Pending”,直到有其他协程从队列中取出元素并调用 task_done(),使得队列剩余空间大于 0,事件循环才会重新调度该生产者协程继续执行 put 操作。这种行为是异步非阻塞 I/O 模型下的典型背压(Backpressure)机制,它有效地将下游处理能力不足的压力反馈给上游,防止内存爆炸。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










