全局数据
同一份数据,随机取数
同一份数据,顺序取数
每个worker节点拥有独立的一份数据 & 不重复
通过init事件注册监听,可结合init_command_line_parser事件配置全局数据,数据针对worker独立唯一。
def work_id_data():"""队列获取作品ID数据"""# work_ids = queue.Queue()with open('work_id.txt', 'r', encoding='utf-8') as f:for i in f.readlines()[int(os.environ.get('first_index')):int(os.environ.get('last_index'))]:work_ids.put_nowait(int(i.strip('\n')))return work_ids@events.init_command_line_parser.add_listenerdef add_user_parser(parser, **kwargs):"""自定义locust命令参数"""parser.add_argument("-fi","--first_index",help="获取截取列表首索引""[fc:]",default=0,type=str)parser.add_argument("-li","--last_index",help="获取截取列表末索引""[:li]",default=0,type=str)args = parser.parse_args()if args.first_index:os.environ['first_index'] = args.first_indexif args.last_index:os.environ['last_index'] = args.last_index@events.init.add_listenerdef on_locust_init(environment, **kwargs):print("当前环境变量first_index为: %s" % os.environ.get('first_index'))print("当前环境变量last_index为: %s" % os.environ.get('last_index'))work_id_data()print('初始化测试数据完毕')if isinstance(environment.runner, MasterRunner):print("master节点执行")else:print("worker节点执行")if __name__ == "__main__":file_name = os.path.abspath(__file__)os.system(f'locust -f {file_name} --master --first_index 0 --last_index 1000')
非全局数据
动态入参,与上下文无联系(例如时间戳、uuid)
动态入参,与上下文联系(请求数据递增版本号)
通过函数方法调用,以字典方式存储,结合类属性定义索引,动态取数,数据针对模拟用户独立唯一。
def version_id_data():"""生成version_ids字典"""version_id = []for i in range(1000000):version_id.append(i)version_ids = dict(zip(version_id, version_id))return version_idsclass ApiUser(TaskSet):"""压测op操作"""index = 1@task(15)def test_op(self):"""op操作"""all_locusts_spawned.wait() # 限制在所有用户准备完成前处于等待状态self.client.send('42["operation",{'f'"revision":{self.user.version_id.get(self.index)}'',"op":[[["extra","user_state","275127340","current_stage_actor",{"r":true,"i":'f'"{uuid.uuid1()}"''}]]]}]')self.index += 1
