【发布时间】:2020-08-07 08:52:04
【问题描述】:
我正在使用resilience4j-spring-boot2 库(io.github.resilience4j:resilience4j-spring-boot2,版本1.5.0)和Spring Boot 版本2.3.1.RELEASE。
我创建了一个RateLimiter,它应该只让一个线程每 30 秒执行一次某个方法。但是,线程调用该方法似乎没有界限(Tomcat服务器中运行的配置线程数除外)。
我实现了一个简单的服务,它等待给定的时间然后返回“Hello!”:
@RequestMapping("/")
@RestController
public class ResilientService {
@RateLimiter(name = "hello-rl")
@GetMapping("/hello/{timeout}")
public String hello(@PathVariable int timeout) throws InterruptedException {
Thread.sleep(timeout);
return "Hello!";
}
}
并配置Ratelimiter如下
resilience4j.ratelimiter:
instances:
hello-rl:
limitForPeriod: 1 # The number of permissions available during one limit refresh period
limitRefreshPeriod: 30s # The period of a limit refresh. After each period the rate limiter sets its permissions count back to the limitForPeriod value
timeoutDuration: 30s # The default wait time a thread waits for a permission
我用八个线程调用了服务:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
@Slf4j
public class CircuitBreakerTest {
@Autowired
TestRestTemplate testRestTemplate;
@LocalServerPort
private int port;
@Value("${server.address}")
private String serverAddress;
@Test
public void t() throws InterruptedException {
final ExecutorService executorService = Executors.newFixedThreadPool(8);
for (int i : IntStream.rangeClosed(1, 8).toArray()) {
executorService.execute(() -> log.error(callService()));
}
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
}
private String callService() {
return testRestTemplate.getForObject(
"http://" + serverAddress + ":" + port + "/hello/5000",
String.class
);
}
输出如下:
2020-08-07 10:41:10,095 ERROR [pool-1-thread-7] CircuitBreakerTest: Hello!
2020-08-07 10:41:10,095 ERROR [pool-1-thread-1] CircuitBreakerTest: Hello!
2020-08-07 10:41:10,095 ERROR [pool-1-thread-8] CircuitBreakerTest: Hello!
2020-08-07 10:41:10,095 ERROR [pool-1-thread-2] CircuitBreakerTest: Hello!
2020-08-07 10:41:10,095 ERROR [pool-1-thread-5] CircuitBreakerTest: Hello!
2020-08-07 10:41:15,104 ERROR [pool-1-thread-3] CircuitBreakerTest: Hello!
2020-08-07 10:41:15,121 ERROR [pool-1-thread-4] CircuitBreakerTest: Hello!
2020-08-07 10:41:15,121 ERROR [pool-1-thread-6] CircuitBreakerTest: Hello!
似乎一次只允许五个线程执行该方法,但我不知道为什么。 Tomcat 服务器以 >8 个线程运行。 我犯错了吗?还是我误解了 RateLimiter 应该如何工作?
【问题讨论】:
-
好吧,如果你调试它,你会看到你的属性被忽略并且默认配置被考虑在内。但是即使在我修复它之后它仍然不起作用,所以没有答案:)
标签: java multithreading spring-boot resilience4j