org.springframework.web.client.HttpClientErrorException: 429 Too Many Requests

 http 429错误码

4.  429 Too Many Requests

   The 429 status code indicates that the user has sent too many
   requests in a given amount of time ("rate limiting").

   The response representations SHOULD include details explaining the
   condition, and MAY include a Retry-After header indicating how long
   to wait before making a new request.

   For example:

   HTTP/1.1 429 Too Many Requests
   Content-Type: text/html
   Retry-After: 3600

   <html>
      <head>
         <title>Too Many Requests</title>
      </head>
      <body>
         <h1>Too Many Requests</h1>
         <p>I only allow 50 requests per hour to this Web site per
            logged in user.  Try again soon.</p>
      </body>
   </html>

   Note that this specification does not define how the origin server
   identifies the user, nor how it counts requests.  For example, an
   origin server that is limiting request rates can do so based upon
   counts of requests on a per-resource basis, across the entire server,
   or even among a set of servers.  Likewise, it might identify the user
   by its authentication credentials, or a stateful cookie.

   Responses with the 429 status code MUST NOT be stored by a cache.

HttpClientErrorException for status HTTP 429 Too Many Requests

用户在在指定的时间里发送了太多的请求。用于限制速率。属于客户端异常,既客户端没有遵守服务端给定的一定频率内的限制访问次数。

一般而言,当服务端检测到客户端在短时间内频繁的尝试访问特定页面时,它会触发速率限制功能。最常见的例子是用户(或攻击者)反复多次地尝试调用登录接口。

所以当出现429错误的时候,就意味着有一个用户或一段代码被太多次的请求,继而触发了服务端的限速功能。

解决方式

收到429状态码并不是一个常规意义上的错误,因为你的请求率太高了,服务器已经被搞的受不了了。所以我们可以把他理解为服务端“友好”要求客户端降低请求频率。

1)让进程休眠。服务器通常在响应中包含一个Retry-after头,其中包含在重试之前应该等待的秒数。请记住,休眠进程可能会导致问题,例如在任务队列中,你应该在稍后重试该任务,以释放该工作进程用于其他事情。

if response.status_code == 429:
time.sleep(int(response.headers["Retry-After"]))

2)指数退避算法。如果服务器没有告诉您需要等待多长时间,那么您可以通过增加暂停时间来重试请求。还可以避免因为任务重试中的集中请求而被再次限流。因为重试时又会有大量的请求在同一时刻涌入,会不断地造成限流。

3)令牌桶。如果您提前知道在给定的时间内能够发出多少请求,那么这种技术就很有用。每次访问API时,首先从桶中获取一个令牌。桶以恒定的速度重新装满。如果桶是空的,我们就知道再次访问API之前必须等待。

如果服务端的限速配置的不正确那就是另外一回事了。由于大多数速率限制是通过IP来标识访问者,这可能会在动态共享IP的场景中出现问题。如果一个人都没有发几个请求,但是一直收到429状态码的话,可以联系服务端的配置人员。 

参考文章 

https://www.rfc-editor.org/rfc/rfc6585#page-3

https://developer.aliyun.com/article/748634

https://www.docs4dev.com/apidocs/zh/spring/5.2.12.RELEASE/org/springframework/web/client/HttpClientErrorException.TooManyRequests.html

本篇文章如有帮助到您,请给「翎野君」点个赞,感谢您的支持。

首发链接:https://www.cnblogs.com/lingyejun/p/16440398.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值