Python|Python3之百万并发实现方法( 二 )


#!/usr/bin/env python# -*- coding: utf-8 -*-import asynciofrom aiohttp import ClientSessiontasks = []async def request_run(i):async with ClientSession() as session:async with session.get(url='http://www.baidu.com/') as response:response = await response.read()print(i)print(response)return responsedef run():for i in range(5):task = asyncio.ensure_future(request_run(i))tasks.append(task)result = loop.run_until_complete(asyncio.gather(*tasks))print(result)if __name__ == '__main__':loop = asyncio.get_event_loop()run()关于ValueError: too many file descriptors in select()异常解决办法
假如你的并发达到2000个 , 程序会报错:ValueError: too many file descriptors in select() 。 报错的原因字面上看是 Python 调取的 select 对打开的文件有最大数量的限制 , 这个其实是操作系统的限制 , linux打开文件的最大数默认是1024 , windows默认是509 , 超过了这个值 , 程序就开始报错 。 这里我们有三种方法解决这个问题:
1.限制并发数量 。 (一次不要塞那么多任务 , 或者限制最大并发数量)
2.使用回调的方式 。
3.修改操作系统打开文件数的最大限制 , 在系统里有个配置文件可以修改默认值 , 具体步骤不再说明了 。
不修改系统默认配置的话 , 个人推荐限制并发数的方法 , 设置并发数为500 , 处理速度更快 。
#!/usr/bin/env python# -*- coding: utf-8 -*-import asyncioimport timefrom aiohttp import ClientSessiontasks = []a = time.time()async def request_run(i, semaphore):async with semaphore:async with ClientSession() as session:async with session.get(url='https://segmentfault.com/q/1010000011211509') as response:response = await response.read()tasks.append(i)# 可以存储返回结果async def run():semaphore = asyncio.Semaphore(500)to_get = [request_run(i, semaphore) for i in range(1000)]# 总共1000任务await asyncio.wait(to_get)if __name__ == '__main__':loop = asyncio.get_event_loop()loop.run_until_complete(run())loop.close()print(tasks)b = time.time()print(b-a)#计算机# #python# #Python基础# #软件开发# #科技新星创作营#

Python|Python3之百万并发实现方法
本文插图


Python|Python3之百万并发实现方法
本文插图


Python|Python3之百万并发实现方法
本文插图


推荐阅读