Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.manager.wealth</groupId>
<artifactId>rate-limiter-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>22</maven.compiler.source>
<maven.compiler.target>22</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>3.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.bucket4j/bucket4j-core -->
<dependency>
<groupId>com.bucket4j</groupId>
<artifactId>bucket4j-core</artifactId>
<version>8.7.0</version>
</dependency>
</dependencies>
</project>
RateLimiterService
package com.ratelimiter.demo.services;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;
@Service
public class RateLimiterService {
private static final int CAPACITY = 5; // Max number of requests allowed
private static final Duration REFILL_DURATION = Duration.ofMinutes(1); // Refill duration
private static final int REFILL_AMOUNT = 5; // Number of requests refilled every minute
private final AtomicInteger requests = new AtomicInteger(0); // Count for requests
private final Bucket bucket;
public RateLimiterService() {
this.bucket = Bucket.builder()
.addLimit(Bandwidth.simple(REFILL_AMOUNT, REFILL_DURATION)) // Limit configuration
.build();
}
public boolean tryConsume() {
return bucket.tryConsume(1); // Tries to consume 1 token
}
public boolean isRateLimitExceeded() {
return !tryConsume();
}
public int getRemainingTokens() {
return (int) bucket.getAvailableTokens();
}
}
RateLimitController
package com.ratelimiter.demo.rest;
import com.ratelimiter.demo.services.RateLimiterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RateLimitController {
@Autowired
private RateLimiterService rateLimiterService;
@GetMapping("/api/resource")
public String accessResource() {
if (rateLimiterService.isRateLimitExceeded()) {
return "Rate limit exceeded. Try again later.";
}
return "Access granted to the resource!";
}
@GetMapping("/api/rateLimitStatus")
public String rateLimitStatus() {
return "Remaining requests: " + rateLimiterService.getRemainingTokens();
}
}
Comments
Post a Comment
Share your thoughts here...