最近公司需要对服务进行性能测试,但是服务不开放http服务,都是rpc接口,如果用httprpc开放后,再进行测试,必然会产生性能损耗,测试结果不准确,那么就需要直接对grpc接口进行性能测试,那现在我们开始吧!
本篇文章建立在,你已经编写了触发grpc的方法
底下的run方法是我已经写好的触发rpc的方法
# -*- coding: utf-8 -*-
import time
from util import run
from locustimport events, User
class GrpcClient(object):
"""重写self.client"""
_locust_environment =None
def connect(self, name, grpc_env, path, parms):
"""重写connect方法"""
start_time =int(time.time())
try:
# 记录开始时间
env = get_env(grpc_env)
res = run(env, path, parms)
except Exception as e:
total_time =int((time.time() - start_time) *1000)
events.request_failure.fire(
request_type='grpc',
name=name,
response_time=total_time,
exception=e
)
else:
total_time =int((time.time() - start_time) *1000)
events.request_success.fire(
request_type='grpc',
name=name,
response_time=total_time,
response_length=0
)
return res
class GrpcUser(User):
abstract =True
def __init__(self, *args, **kwargs):
super(GrpcUser, self).__init__(*args, **kwargs)
self.client = GrpcClient()
然后下面是调用类
class BasicUser(GrpcUser):
"""
压测任务类
执行压测命令: locust -f locust_file.py -u 10 -r 3 --headless
参数信息详见locust官方网站:https://docs.locust.io/en/latest/running-locust-without-web-ui.html
"""
wait_time = between(2,
5) # locust自带环境配置参数,详见 https://docs.locust.io/en/latest/api.html?highlight=between#locust
# .wait_time.between
@task # task压测任务语法糖,可以task(n)设置权重,n越大,任务权重越高
def test(self):
"""获取未认证账号接口性能测试"""
name = "测试" # 任务名称
env = "xxxx" # 服务名称
path = "xxxx" # 服务path
parms = {
"person_user_ids": None, # 参数
"include_resign": None
}
self.client.connect(name=name, grpc_env=env, path=path, parms=parms) # 调用重写后的connect方法,触发压测任务
是不是很简单 哈哈,加油~