压测:Locust测试结束后,实时信息推送
一、需求:反馈机制
压测结束后,企业微信实时反馈信息给项目组。
二、问题:
记录到Redis里面的数据,在Locust Teardown时,是每个worker都发送一份消息
三、解决方案:
- Redis增加Lock
import redis_lock
from locust import HttpLocust
from script import Task
from userid.qstools import set_user_info
from userid.rclient import get_lottery_distribution, set_distribution_state, flush_data
from lib.redis_pool import RedisPool
r = RedisPool().redis_conn
class LocustTask(HttpLocust):
task_set = Task
# 可修改默认多个任务间的等待时间
min_wait = 10
max_wait = 10
# 清空Redis数据
flush_data()
set_user_info()
# 设置消息发送状态(默认 True)
set_distribution_state()
def teardown(self):
# Redis加锁
with redis_lock.Lock(r, "redis-lock"):
# 抽奖统计
get_lottery_distribution()
if __name__ == '__main__':
t = LocustTask()
t.run()
2.抽奖统计
import json
from lib.redis_pool import RedisPool
from lib.webhook import WebHook
r = RedisPool().redis_conn
def set_distribution_state(state=True):
r.set('lottery_distribution', json.dumps(state))
def get_distribution_state():
return r.get('lottery_distribution')
def increase_lottery(lottery):
lottery = json.loads(lottery, encoding='utf8')
if 'Result' in lottery:
r.incr(lottery['lottery']['Type'])
elif 'tip' in lottery:
r.incr(lottery['message']['title'])
def get_lottery_distribution():
if get_distribution_state() == 'true':
# 已推送消息,设为False
set_distribution_state(state=False)
distribution = {'特等奖': r.get('特等奖'),
'一等奖': r.get("一等奖"),
'二等奖': r.get("二等奖"),
'三等奖': r.get("三等奖"),
'安慰奖': r.get("安慰奖"),
'未获奖品': r.get("抱歉")}
print(f'抽奖统计: {distribution}')
WebHook.push_msg(json.dumps(distribution, ensure_ascii=False))
- 企业微信推送
import time
import json
import requests
class WebHook:
WEIXIN_WEBHOOK_URI = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx"
@classmethod
def push_msg(cls, msg: str):
project = 'Lottery'
# 组合要推送的消息
data = {
"msgtype": "markdown",
"markdown": {
"content": f"##### 压测项目消息推送,请相关同学注意👀,当前项目: "
f'**<font color="info">{project}</font>**\n'
f">详细信息:\t\t**<font color='red'>{msg}</font>**\n"
"> \n"
f">触发时间:\t\t{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}"
"> \n"
},
}
weixin_response = requests.post(url=cls.WEIXIN_WEBHOOK_URI, data=json.dumps(data))
return weixin_response.status_code