Spring Boot集成Resilience4j @RateLimiter未触发限流如何解决?
问题排查结果
核心故障原因
- 自调用绕过AOP代理:Resilience4j的限流逻辑基于Spring AOP代理实现,只有被
@RateLimiter注解修饰的方法被类外部的其他对象调用时,才会触发代理拦截逻辑。你在同一个类的run方法中直接调用本类的callBackendA()属于类内部自调用,不会走代理流程,自然无法触发限流规则。 - 方法访问权限不符合要求:Spring AOP默认仅支持对
public修饰的方法进行代理增强,你当前的callBackendA是private私有方法,无法被AOP拦截,注解不会生效。
修复方案
方案1(推荐):将限流方法抽为独立Bean
- 单独定义服务类存放限流方法,方法修饰符改为public
@Log4j2 @Component public class BackendService { @RateLimiter(name = "backendA") public void callBackendA() { log.info("Calling "); } }
- 在原逻辑类中注入该Bean后调用
@Log4j2 @Component class Resilience4jDemo implements CommandLineRunner { @Autowired private BackendService backendService; @Override public void run(String... args) throws Exception { for (int i = 0; i < 100; i++) { backendService.callBackendA(); } } }
方案2:使用代理上下文调用本类方法
- 在application.yaml中添加配置暴露代理对象
spring: aop: expose-proxy: true
- 调整原方法调用逻辑,同时将限流方法改为public
@Log4j2 @Component class Resilience4jDemo implements CommandLineRunner { @Override public void run(String... args) throws Exception { Resilience4j proxy = (Resilience4j) AopContext.currentProxy(); for (int i = 0; i < 100; i++) { proxy.callBackendA(); } } @RateLimiter(name = "backendA") public void callBackendA() { log.info("Calling "); } }
内容的提问来源于stack exchange,提问作者Rajvansh
相关产品推荐
相关产品推荐

