前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >org.springframework.web.client.HttpClientErrorException: 429 Too Many Requests

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

作者头像
翎野君
发布2023-05-12 20:30:55
4090
发布2023-05-12 20:30:55
举报
文章被收录于专栏:翎野君翎野君

 http 429错误码

代码语言:javascript
复制
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头,其中包含在重试之前应该等待的秒数。请记住,休眠进程可能会导致问题,例如在任务队列中,你应该在稍后重试该任务,以释放该工作进程用于其他事情。

代码语言:javascript
复制
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://www.docs4dev.com/apidocs/zh/spring/5.2.12.RELEASE/org/springframework/web/client/HttpClientErrorException.TooManyRequests.html

首发链接:https://cloud.tencent.com/developer/article/2285740

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-07-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  •  http 429错误码
  • HttpClientErrorException for status HTTP 429 Too Many Requests
  • 解决方式
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档