DevShivmohan / Learning-everything

Learning for developer only
0 stars 1 forks source link

Spring boot API rate limiting #33

Open DevShivmohan opened 1 year ago

DevShivmohan commented 1 year ago

Make limit of an API

Add maven dependency of Bucket4j

<dependency>
    <groupId>com.github.vladimir-bukhtoyarov</groupId>
    <artifactId>bucket4j-core</artifactId>
    <version>4.10.0</version>
</dependency>

Declare as a bean of Bucket

/**
     * 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();
    }