Azure托管磁盘快照创建的Python异步代码实现方案咨询
批量创建Azure托管磁盘快照的异步实现方案
方案选择建议
- 新手优先选线程池:基于现有同步Azure SDK改造,代码改动小,逻辑直观,容易调试。
- 追求效率选Asyncio:搭配Azure异步SDK,IO开销更低,适合大规模批量操作,但需要掌握基础异步编程概念。
方案一:线程池实现(适合新手)
基于Python标准库concurrent.futures,复用原同步版compute_client,并行提交快照任务并实时处理结果:
from concurrent.futures import ThreadPoolExecutor, as_completed def process_single_snapshot(vm, compute_client): # 提交快照创建请求,等待该任务完成 poller = compute_client.snapshots.begin_create_or_update(vm.name, vm.location) snapshot = poller.result() # 处理就绪的快照(示例:打印信息、写入记录等) print(f"快照处理完成:{snapshot.name} | ID: {snapshot.id}") return snapshot def batch_create_snapshots(list_of_vms, compute_client): # 线程池大小根据Azure并发配额调整(建议10-20) with ThreadPoolExecutor(max_workers=15) as executor: # 批量提交所有VM的快照任务 future_map = {executor.submit(process_single_snapshot, vm, compute_client): vm for vm in list_of_vms} # 实时获取完成的任务,处理结果(不阻塞其他任务执行) for future in as_completed(future_map): vm = future_map[future] try: future.result() print(f"VM {vm.name} 的快照流程已结束") except Exception as e: print(f"VM {vm.name} 创建快照失败: {str(e)}")
方案二:Asyncio异步实现(高效并发)
使用Azure异步SDK(azure.mgmt.compute.aio),通过async/await实现非阻塞并发,资源开销更低:
import asyncio from azure.mgmt.compute.aio import ComputeManagementClient async def process_single_snapshot_async(vm, async_compute_client): # 异步提交快照创建请求,等待任务完成 poller = await async_compute_client.snapshots.begin_create_or_update(vm.name, vm.location) snapshot = await poller.result() # 处理就绪的快照 print(f"快照处理完成:{snapshot.name} | ID: {snapshot.id}") return snapshot async def batch_create_snapshots_async(list_of_vms, async_compute_client): # 创建所有异步任务 tasks = [process_single_snapshot_async(vm, async_compute_client) for vm in list_of_vms] # 实时处理完成的任务 for task in asyncio.as_completed(tasks): try: await task print(f"一个快照流程已结束") except Exception as e: print(f"快照创建失败: {str(e)}") # 主执行入口 async def main(): # 初始化异步Compute客户端(替换为你的认证信息和订阅ID) async_compute_client = ComputeManagementClient(your_credential, your_subscription_id) await batch_create_snapshots_async(list_of_virtual_machines, async_compute_client) # 关闭异步客户端 await async_compute_client.close() if __name__ == "__main__": asyncio.run(main())
注意事项
- Azure API有并发配额限制,线程池大小或异步任务数量不要设置过高(建议参考Azure官方配额文档)。
- 两种方案都需做好异常捕获,避免单个任务失败导致整体流程中断。
- 同步版
compute_client是线程安全的,可直接在多线程中复用;异步版客户端需遵循异步编程规范使用。
内容的提问来源于stack exchange,提问作者Azure Newbie
相关产品推荐
相关产品推荐

