Python多线程实现支付模拟请求过程解析
作者:yaominghui 发布时间:2023-04-09 17:59:35
标签:python,多,线程,支付
思路:
队列使用说明:
multiprocessing.Queue()#用于进程间通信,单主进程与子进程无法通信(使用进程池时尽量不要使用这个)
multiprocessing.Manager().Queue()#用于主子进程通信,通过进程池(pool)创建的进程可以数据共享
queue.Queue()#用于线程间通信,同一进程内的数据可以共享
1.从数据库里获取待支付的订单
2.将获取出来的数据添加至队列(queue.Queue()),并在函数中返回消息队列的长度
3.根据队列长度创建对应的线程数量
4.把创建的线程放在list
5.依次启动
6.最后等待主线程执行完结束,统计函数运行时长
代码如下
import asyncio
import sys
from queue import Queue
sys.path.append("../")
from tool.__init__ import *
from tool.decorator_token import *
import time
from threading import Thread,Lock
class doWeChatNotify(BaseTest):
def __init__(self):
super().__init__()
self.limit_num=100 #查询记录条数
self.WeChatNotify_sql='''select order_id,order_sn from fw_order where `status`=0
and course_id=1569 ORDER BY create_time desc limit %d ;'''%(self.limit_num)
self.fwh_test_api=fwh_test_api
self.data = self.my_op.sql_operation_fwh(self.WeChatNotify_sql)
self.fwh_order_dict = {}
self.que = Queue()
@token_fwh#验证token有效性
def get_fwh_token_list(self):
token_list=self.fwh_token.loadTokenList()
return token_list
@token_crm#验证token有 def get_crm_token_list(self) token_list=self.token.loadTokenList()
return token_list
def testDoWeChatNotify(self):
DoWeChatNotify_file='../tokenFileAndtxtFiles'+'/'+"DoWeChatNotify_asynchronousPay.txt"
with open(DoWeChatNotify_file,'a',encoding='utf=-8') as file:
str_first="order_id\t"+"order_sn\t\n" #文件首行数据
file.write(str_first)
fwh_order_id_list, fwh_order_sn_list = [], []
if self.data!=():
for a in self.data:
fwh_order_id=a['order_id']
fwh_order_sn=a['order_sn']
self.fwh_order_dict[fwh_order_id]=fwh_order_sn
with open(DoWeChatNotify_file,'a',encoding='utf-8') as file2:#文件写入
str_DoWeChatNotifyInfo=str(fwh_order_id)+'\t'+str(fwh_order_sn)+'\t\n'
file2.flush() #清除缓冲区
file2.write(str_DoWeChatNotifyInfo)
self.que.put(self.fwh_order_dict)#将数据添加至队列
#关闭数据库连接
# self.my_op.close_db_fwh()
# self.my_op.close_db()
return self.que.qsize()#返回队列数量
def asynchronousPay(self,order_id,order_sn):
count=1
count_num=50
token_list=self.get_fwh_token_list()
if (self.data!=()):
headers_form_urlencoded['token']=token_list[0]
url_wechat_success_huidiao=self.fwh_test_api+'/index/Order/doWeChatNotify'
data_wechat_success_huidiao=self.data_to_str.requestDataToStr_firefoxAndChrome_fwh('''order_sn:{}
order_id:{}
meth_id:4
timestamp:157129653969
sign:0687b01b300b9e300d3996a9d2173f1380973e5a'''.format(order_sn,order_id))
request_wechat_success_huidiao=requests.post(url=url_wechat_success_huidiao,headers=headers_form_urlencoded,data=data_wechat_success_huidiao)
response_wechat_success_huidiao=request_wechat_success_huidiao.json()
if '订单状态错误,非待支付订单' in response_wechat_success_huidiao['msg']:
print(data_wechat_success_huidiao)
else:
print('待支付订单为空')
def run_multithreading(self):#多线程
threads = []#存放所有的线程
nloops = list(range(self.testDoWeChatNotify()))#获取队列数量
if len(nloops)>0:
for i,k in zip(nloops,self.que.get().items()):#根据队列数量来创建线程
t = Thread(target=self.asynchronousPay,args=(k[0],k[1]))
threads.append(t)
for s in nloops: # 开始多线程
threads[s].start()
for j in nloops: # 等待所有线程完成
threads[j].join()
else:
print("队列数量为空")
if __name__=="__main__":
start_time = time.time() # 计算程序开始时间
wechfy=doWeChatNotify()
wechfy.run_multithreading()#多线程
print('程序耗时{:.2f}'.format(time.time() - start_time)) # 计算程序总耗时
总结:亲测运行时间还是会快很多,单线程支付100个订单四十几秒的样子,多线程运行不用join2.x秒,用join八秒的样子,还有很大的优化空间,因为运行时会创建100个线程
来源:https://www.cnblogs.com/qtclm/p/12116250.html


猜你喜欢
- 简单的for循环打印三角形1,for循环方法实现星星三角代码:for i in range(0,5):for j in range(i+1)
- 词云图from pyecharts.charts import WordClouddef word1(): words= [ &
- 核心代码function convert2utf8($string) { return iconv(&
- 今天在GOOGLE上查图片资料,这一幕真让我纠结啊:使用【向前】【向后】这种说法,就默认了有一个对比坐标,那就是当前显示的4张缩略图。点击【
- PyHook是一个基于Python的“钩子”库,主要用于监听当前电脑上鼠标和键盘的事件。这个库依赖于另一个Python库PyWin32,如同
- 通过启用php.ini配置文件中的相关选项,就可以将大部分想利用SQL注入漏洞的骇客拒绝于门外。 开启magic_quote_gpc=on之
- 第一步、导入需要的包import osimport scipy.io as sioimport numpy as npimport torc
- 1、说明创建堆有两种基本方法:heappush() 和 heapify()。当使用heappush()时,当新元素添加时,堆得顺序被保持了。
- 在很多的情况下,在编写存储过程中往往会用到数组,但是mysql中存储过程传入参数并没有可以直接传入数组的方法。在这种情况下我们只能退而求之或
- 前端版本更新检查,实现页面自动刷新使用vite对项目进行打包,对 js 和 css 文件使用了 chunkhash 进行了文件缓存控制,但是
- iamlaosong文曾经看到这样一个问题,一个字典中的元素是列表,将这个列表元素赋值给一个变量,然后修改这个列表中元素的值,结果发现,字典
- 在上一篇博客中,已经将环境搭建好了。现在,我们利用搭建的环境来运行一条测试脚本,脚本中启动一个计算器的应用,并实现加法的运算。创建模拟器在运
- 1 安装nginx下载windows上的nginx最新版本,http://www.nginx.org/en/download.html。解压
- 1、先介绍如何用PHP连上数据库(数据库用户名“root”,密码“sun”,有库“myguestbook”) 图62、PHP和My
- 本文实例讲述了Python随机数用法。分享给大家供大家参考,具体如下:1. random.seed(int)给随机数对象一个种子值,用于产生
- 基本原理选好画板大小,设置好画笔颜色、粗细,定位好位置,依次画鼻子、头、耳朵、眼睛、腮、嘴、身体、手脚、尾巴,完事儿。都知道,T
- 1、使用MySQLdb读取出来的数据是unicode字符串,如果要写入redis的hash中会变成"{u'eth0_out
- 一、背景及研究现状在我国互联网的发展过程中,PC互联网已日趋饱和,移动互联网却呈现井喷式发展。数据显示,截止2013年底,中国手机网民超过5
- 随机生成四位数验证码,包括汉字,数字,英文大小写。1.Servlet类package servlet;import java.awt.Bas
- 详细代码见仓库github地址:github.com/nerkeler/account重要提示程序默认密码:password密钥位置:./r