在 spring boot 中捕获 resilience4j 的限流异常,核心做法是配置全局异常处理器并注册 `resilience4jspringbootautoconfiguration` 提供的 `retryaspect` 或 `bulkheadaspect` 等切面。当限流触发时,底层会抛出 `io.github.resilience4j.circuitbreaker.callnotpermittedexception`(熔断)或 `io.github.resilience4j.ratelimiter.requestnotpermitted`(限流)。通过实现 `@controlleradvice` 并添加 `@exceptionhandler(requestnotpermitted.class)`,即可拦截该异常并返回自定义的 http 429 too many requests 响应。

如何配置全局异常处理器以拦截 RequestNotPermitted
要实现这一目标,需要创建一个继承自 `ResponseEntityExceptionHandler` 或标注为 `@RestControllerAdvice` 的类,并在其中定义针对 `RequestNotPermitted` 的处理方法。该方法应返回一个包含错误信息的 `ResponseEntity` 对象,状态码设为 429。同时,确保项目中引入了 `resilience4j-spring-boot2` 依赖,以便自动装配相关的 AOP 切面,使限流注解生效并能正确抛出异常。

import io.github.resilience4j.ratelimiter.RequestNotPermitted;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RequestNotPermitted.class)
public ResponseEntity<string> handleRateLimiterExceeded(RequestNotPermitted ex) {
return ResponseEntity
.status(HttpStatus.TOO_MANY_REQUESTS)
.body("Rate limit exceeded. Please try again later.");
}
}</string>
如何在 Controller 中结合限流注解使用
在具体的业务 Controller 中,只需在需要限流的方法上添加 `@RateLimiter` 注解,并指定名称。当请求频率超过配置的限制时,Resilience4j 会自动抛出 `RequestNotPermitted` 异常,进而被上述的全局异常处理器捕获。这种解耦方式使得业务代码无需处理复杂的限流逻辑,专注于业务本身,而异常处理则统一由全局控制器管理。

import io.github.resilience4j.ratelimiter.annotation.RateLimiter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/api/data")
@RateLimiter(name = "myRateLimiter")
public String getData() {
return "Data fetched successfully";
}
}
限流异常中的 retryWaitDuration 参数如何影响行为
当 `RequestNotPermitted` 被抛出时,其内部包含了一个 `retryWaitDuration` 字段,表示客户端应该等待多久后再重试。这个值由 `RateLimiterConfig` 中的 `waitDuration` 属性决定。在全局异常处理中,你可以读取这个字段并将其放入 HTTP 响应的 `Retry-After` 头中,从而指导客户端进行指数退避重试,而不是立即重新发起请求导致持续被限流。











