Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 288
Vimit Dhawan Avatar asked Oct 16 '25 03:10

Vimit Dhawan


1 Answers

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.

like image 151
Tom Van Rossom Avatar answered Oct 17 '25 21:10

Tom Van Rossom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!