工作进程函数,模拟多个用户同时请求API密钥
(worker_id, num_requests, sources=None, req_queue=None, res_queue=None)
| 248 | logger.info("\nAPI密钥轮询测试完成") |
| 249 | |
| 250 | def worker_process(worker_id, num_requests, sources=None, req_queue=None, res_queue=None): |
| 251 | """工作进程函数,模拟多个用户同时请求API密钥""" |
| 252 | if sources is None: |
| 253 | sources = get_available_sources() # 使用过滤后的可用源 |
| 254 | |
| 255 | local_success = 0 |
| 256 | local_failure = 0 |
| 257 | api_keys_used = {} |
| 258 | |
| 259 | logger.info(f"工作进程 {worker_id} 启动,将执行 {num_requests} 个请求") |
| 260 | |
| 261 | # 如果使用请求队列模式 |
| 262 | if req_queue is not None and res_queue is not None: |
| 263 | for _ in range(num_requests): |
| 264 | try: |
| 265 | # 从队列中获取任务 |
| 266 | task = req_queue.get(timeout=1) |
| 267 | source_name = task['source_name'] |
| 268 | |
| 269 | # 获取API密钥 |
| 270 | api_key = get_api_key(source_name) |
| 271 | if api_key: |
| 272 | # 记录使用的API密钥 |
| 273 | if api_key not in api_keys_used: |
| 274 | api_keys_used[api_key] = 0 |
| 275 | api_keys_used[api_key] += 1 |
| 276 | |
| 277 | # 随机决定是成功还是失败 |
| 278 | status = random.random() < SUCCESS_RATE |
| 279 | |
| 280 | # 记录API密钥使用情况 |
| 281 | if record_api_key_usage(api_key, source_name, status=status): |
| 282 | if status: |
| 283 | local_success += 1 |
| 284 | else: |
| 285 | local_failure += 1 |
| 286 | logger.info(f"进程 {worker_id} - 请求: 源 {source_name} - 状态 {'成功' if status else '失败'}") |
| 287 | else: |
| 288 | local_failure += 1 |
| 289 | logger.error(f"进程 {worker_id} - 请求: 记录使用情况失败") |
| 290 | else: |
| 291 | local_failure += 1 |
| 292 | logger.error(f"进程 {worker_id} - 请求: 获取API密钥失败") |
| 293 | |
| 294 | # 标记任务完成 |
| 295 | req_queue.task_done() |
| 296 | |
| 297 | except queue.Empty: |
| 298 | # 队列为空,可能所有任务已分发完 |
| 299 | break |
| 300 | except Exception as e: |
| 301 | logger.error(f"工作进程 {worker_id} 处理任务时出错: {str(e)}") |
| 302 | local_failure += 1 |
| 303 | if req_queue is not None: |
| 304 | req_queue.task_done() |
| 305 | |
| 306 | # 随机短暂延迟,模拟真实请求间隔 |
| 307 | time.sleep(random.uniform(0.1, 0.3)) |
no test coverage detected