/**
* API rate limiting 5 requests only for 2 minutes beginning of the program after exhausted all tokens it will refill by 2 tokens in every 2 minutes
* @return
*/
@Bean
public Bucket bucket(){
return Bucket4j.builder().addLimit(Bandwidth.classic(5, Refill.intervally(2, Duration.ofMinutes(2)))).build();
}
Using at Controller layer of API level
@Autowired
private Bucket bucket;
/**
* It will consume 1 token in every request
* @return
* @throws CustomException
*/
@GetMapping("/play")
public ResponseEntity<?> getQuestion() throws CustomException {
System.out.println("Available tokens-"+bucket.getAvailableTokens());
if(!bucket.tryConsume(1))
throw new CustomException(HttpStatus.TOO_MANY_REQUESTS.value(), "API request limit exceeded");
return questionService.getQuestion();
}
Make limit of an API
Add maven dependency of Bucket4j
Declare as a bean of Bucket
Using at Controller layer of API level