我似乎無法讓 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>
沒有進行速率限制。無法弄清楚我錯過了什么。
uj5u.com熱心網友回復:
我沒有使用 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();
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/368487.html
