How to implement and limit API calls per second in Spring Rest

眉间皱痕 提交于 2021-01-27 12:36:32

问题


I have spring batch application with spring MVC. In this application, I have to call Google API. There is a restriction of max 4 req per sec for API. Now I have to call google API from inside the spring batch. So I have two questions.

q1: How can I implement rest call to Google API. I know about Rest Template but I want that there is any better approach like feign client that we use in microservices.

q2: how can I restrict 4 calls per second.

In case you have any question. Please let me know


回答1:


You can limit API call per second by using a RateLimiter. There is one implemented in Guava

You need to create the RateLimiter and tell how many calls per second.

final RateLimiter rateLimiter = RateLimiter.create(4.0); // rate is "4 permits per second"

Every time you want to limit, you need to acquire a permit. If all permits are used, executions waits.

rateLimiter.acquire(1);

It is also possible to specify a timeout on how long to wait for a permit.




回答2:


in our spring-boot project we use OkHttpClient3 as http client. We also make rest calls to lots of different public APIs. Some of them restricts calls per second. As a solution we implemented an Interceptor called DelayInterceptor.

Basically; create a Java Class that implements okhttp3.Interceptor. In it's public Response intercept(Chain chain) method look for the host you are requesting (to differentiate between calls made to different public APIs) using chain.request().url().host() and if you made a call to this host already use Thread.sleep(amount);

Since our project relatively new, we did not analyze possible drawbacks, but so far it works.

P.S: You can also look into AsyncHttpClient project, which already has a solution for this problem (even though I could not find with a simple google search).




回答3:


I have created RateLimiter that can be used to limit API. It's generic solutions for the thread you can improve and implement for your API.

Rate Limiting API



来源:https://stackoverflow.com/questions/54199734/how-to-implement-and-limit-api-calls-per-second-in-spring-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!