Declarative approach of throttling control over the Spring services.
@Throttling
annotation helps you to limit the number of service method calls per java.util.concurrent.TimeUnit
for a particular user, IP address, HTTP header/cookie value, or using Spring Expression Language (SpEL).
Please see example project. Pull requests are welcome.
TODO
The following throttling configuration allows 1 method calls per SECOND for each unique HttpServletRequest#getRemoteAddr()
.
This is 'defaults' for @Throttling
annotation.
@Throttling
public void serviceMethod() {
}
is the same as:
@Throttling(type = ThrottlingType.RemoteAddr, limit = 1, timeUnit = TimeUnit.SECONDS)
public void serviceMethod() {
}
The following throttling configuration allows 3 method calls per MINUTE for each unique userName in model object passed as parameter, i.e. model.getUserName()
.
Please refer to official docs on SpEL.
@Throttling(type = ThrottlingType.SpEL, expression = "#model.userName", limit = 3, timeUnit = TimeUnit.MINUTES)
public void serviceMethod(Model model) {
log.info("executing service logic for userName = {}", model.getUserName());
}
The following throttling configuration allows 24 method calls per DAY for each unique cookie value retrieved from HttpServletRequest#getCookies()
.
@Throttling(type = ThrottlingType.CookieValue, cookieName = "JSESSIONID", limit = 24, timeUnit = TimeUnit.DAYS)
public void serviceMethod() {
}
The following throttling configuration allows 10 method calls per HOUR for each unique header value retrieved from HttpServletRequest#getHeader('X-Forwarded-For')
.
@Throttling(type = ThrottlingType.HeaderValue, headerName = "X-Forwarded-For", limit = 10, timeUnit = TimeUnit.HOURS)
public void serviceMethod() {
}
The following throttling configuration allows 1 method calls per HOUR for each unique HttpServletRequest#getUserPrincipal().getName()
.
@Throttling(type = ThrottlingType.PrincipalName, limit = 1, timeUnit = TimeUnit.HOURS)
public void serviceMethod() {
}
ThrottlingException
is thrown when method reaches @Throttling
configuration limit. Service method won't be executed.
@ResponseStatus(code = HttpStatus.TOO_MANY_REQUESTS, reason = "Too many requests")
public class ThrottlingException extends RuntimeException {
}
Spring Boot Throttling is Open Source software released under the Apache 2.0 license.