【问题标题】:Can't get Resilience4j @RateLimiter to work with Spring Boot无法让 Resilience4j @RateLimiter 与 Spring Boot 一起使用
【发布时间】:2022-01-05 11:53:40
【问题描述】:

我似乎无法让 Resilience4j @RateLimiter 与 Spring Boot 一起使用。

下面是代码

@Log4j2
@Component
class Resilience4jDemo implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        for (int i = 0; i < 100; i++) {
            callBackendA();
        }
    }

    @RateLimiter(name = "backendA")
    private void callBackendA() {
        log.info("Calling ");
    }
}

application.yaml 文件

resilience4j.ratelimiter:
  instances:
    backendA:
      limitForPeriod: 1
      limitRefreshPeriod: 10s
      timeoutDuration: 0

pom.xml

<!-- https://mvnrepository.com/artifact/io.github.resilience4j/resilience4j-spring-boot2 -->
<dependency>
    <groupId>io.github.resilience4j</groupId>
    <artifactId>resilience4j-spring-boot2</artifactId>
    <version>1.7.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-actuator -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
    <version>2.6.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-aop -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
    <version>2.6.0</version>
</dependency>

没有进行速率限制。无法弄清楚我错过了什么。

【问题讨论】:

  • 这叫做self-call,Spring的AOP都不起作用。

标签: java spring-boot resilience4j


【解决方案1】:

我没有使用 Resilience4j 的经验,但看起来您正在尝试在这里使用 spring-aop。这适用于运行时生成的代理,该代理包装了提供附加功能(在这种情况下为速率限制)的原始类。

如果是这样,你不能注释类的私有方法,因为它不会被代理生成机制检测和处理。

请考虑创建另一个 bean 并将其功能公开为公共方法:

public interface Backend {
   void callBackendA();
}

@Component // this is a spring bean!
@Log4j2
public class LoggingBackendImpl implements Backend {
   @RateLimiter(name = "backendA")
   public void callBackendA() {
      log.info("calling backend");
   }
}


@Component
class Resilience4jDemo implements CommandLineRunner {
    @Autowired
    Backend backend;  // this has to be managed by spring 

    @Override
    public void run(String... args) throws Exception {
        for (int i = 0; i < 100; i++) {
            backend.callBackendA();
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 2020-03-09
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    相关资源
    最近更新 更多