async_request_client.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import asyncio
  2. from typing import Optional, Dict
  3. import aiohttp
  4. from core.utils.log.logger_manager import LoggerManager
  5. class AsyncRequestClient:
  6. """
  7. 请求失败重试,本地日志记录
  8. 请求返回code!=0重试,本地日志记录
  9. 重试达到最大次数后上报阿里云日志
  10. """
  11. def __init__(self, logger:Optional[LoggerManager.get_logger()] = None ,
  12. aliyun_log:Optional[LoggerManager.get_aliyun_logger()] = None,
  13. max_retries=3, timeout=30
  14. ):
  15. self.logger = logger
  16. self.aliyun_log = aliyun_log
  17. self.max_retries = max_retries
  18. self.timeout = timeout
  19. async def request(self, session: aiohttp.ClientSession, method: str, url: str, **kwargs) -> Optional[Dict]:
  20. retries = 0
  21. while retries < self.max_retries:
  22. try:
  23. if self.logger:
  24. self.logger.info(f"请求 {method} {url}, 请求参数{kwargs}")
  25. if self.aliyun_log:
  26. self.aliyun_log.logging(
  27. code = "1012",
  28. message="初始化请求",
  29. data={"utl":url,
  30. "method":method,
  31. "requestBody":kwargs
  32. }
  33. )
  34. async with session.request(method, url, **kwargs) as response:
  35. response.raise_for_status()
  36. resp = await response.json()
  37. if resp.get('code') != 0:
  38. retries += 1
  39. if self.logger:
  40. self.logger.info(f"{url} 响应 {resp}, 重试 {retries}/{self.max_retries}")
  41. if retries >= self.max_retries:
  42. error_msg = f"请求响应code非0且达到最大重试次数 {self.max_retries}"
  43. if self.logger:
  44. self.logger.error(error_msg)
  45. if self.aliyun_log:
  46. self.aliyun_log.logging(
  47. code="9006",
  48. message=error_msg,
  49. data={
  50. "url": url,
  51. "method": method,
  52. "requestBody": kwargs,
  53. "response": resp
  54. }
  55. )
  56. await asyncio.sleep(5)
  57. continue
  58. self.logger.info(f"{url} 响应: {resp}")
  59. return resp
  60. except Exception as e:
  61. retries += 1
  62. if retries >= self.max_retries:
  63. if self.logger:
  64. self.logger.error(f"请求失败达到最大重试次数: {e}")
  65. if self.aliyun_log:
  66. self.aliyun_log.logging(
  67. code="9006",
  68. message="请求异常达到最大重试次数",
  69. data={
  70. "url": url,
  71. "method": method,
  72. "requestBody": kwargs,
  73. "response": resp
  74. }
  75. )
  76. return
  77. if self.logger:
  78. self.logger.warning(f"请求失败 {e}, 重试 {retries}/{self.max_retries}")
  79. await asyncio.sleep(5)