A convenient Spring library that allows you to limit the rate at which annotated methods are called. Based
on Guava's RateLimiter
class.
First, add this spring starter to your project's classpath. Then configure a key with a rate limit (given in permits
per second or queries per second as its sometimes called) in your configuration file. The example below configures
the demo-group key to a limit of 10 permits per second.
tarsiswt.ratelimiter.configuration.demo-group.qps=1Finally add the @Limited annotation to the methods you wish apply the rate limit with the given key:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@Component
class MyRateLimitedComponent {
@Limited(key = "demo-group")
public void rateLimitedMethod() {
}
}Calls made to the rateLimitedMethod will now be subjected to the configured rate limit for its key (demo-group) in
this case.
An @Aspect (especifically RateLimiterAspect) will
intercept calls to methods annotated with @Limited and lookup is corresponding rate limit configuration. Currently
there is only one implementation for the Limiter interface and
that is the GuavaBasedLimiter which is essencially a
wraper for
Guava's RateLimiter
and so the rate limiting works exactly as described in its Javadoc.