Python3 利用asynico协程系统构建生产消费模型

今天研究了下python3的新特性 asynico,试了试aiohttp协程效果,单核QPS在500~600之间,性能还可以。

1import aiohttp 2import asyncio 3import hashlib 4import time 5from asyncio import Queue 6 7 8class Fetch: 9 def __init__(self): 10 self.work_queue = Queue() 11 self.max_loop = 10000 12 self.host = "http://14.29.5.29/XXXX" 13 self.payload = {"planId": 10000007, "activityId": 1002, "label": 1, 14 "key": "98214ecfe6b9ae8855e3ac6509ad940f", "keyType": "imei", 15 "batchId": 1, "token": "395La7f9x9x"} 16 17 async def get_url(self, host, payload): 18 async with aiohttp.ClientSession() as session: 19 async with session.post(host, data=payload) as resp: 20 text = await resp.text() 21 if "1" in text: 22 print(text, payload["key"]) 23 24 async def consumer(self): 25 while True: 26 param = await self.work_queue.get() 27 if param: 28 await self.get_url(self.host, param) 29 self.work_queue.task_done() 30 else: 31 break 32 33 async def producer(self): 34 i = 0 35 string = '866260035710238' 36 while 1: 37 if i: 38 md5_str = hashlib.md5(string.encode('utf-8')) 39 self.payload["key"] = md5_str.hexdigest() 40 string = str(int(string) + 1) 41 await self.work_queue.put(self.payload.copy()) #必须要 42 i += 1 43 if i > self.max_loop: 44 break 45 46 async def run(self): 47 await self.producer() 48 print('start consumer...') 49 50 tasks = [ 51 loop.create_task(self.consumer()) 52 for i in range(10) 53 ] 54 55 await self.work_queue.join() 56 print('end join') 57 for task in tasks: 58 task.cancel() 59 60t1 = time.time() 61loop = asyncio.get_event_loop() 62test = Fetch() 63loop.run_until_complete(test.run()) 64loop.close() 65print(time.time() - t1)
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )