Ira*_* Re 6 reactive-programming rx-java project-reactor spring-webclient
我需要实现以下行为:
429 Too many requests,则最多重试 3 次,延迟 1 秒我想使用 Spring WebClient 来实现此目的,并提出了以下代码:
Mono<ClientResponse> response = webClient.post()
.uri(URI.create("/myuri"))
.body(BodyInserters.fromObject(request))
.retrieve()
.onStatus(httpStatus -> httpStatus.equals(HttpStatus.TOO_MANY_REQUESTS),
response -> Mono.error(new TooManyRequestsException("System is overloaded")))
.bodyToMono(ClientResponse.class)
.retryWhen(Retry.anyOf(TooManyRequestsException.class)
.fixedBackoff(Duration.ofSeconds(1)).retryMax(3))
.doOnError(throwable -> saveToDB(some_id, throwable))
.subscribe(response -> logResponse(some_id, response));
Run Code Online (Sandbox Code Playgroud)
现在我想测试重试机制和错误处理是否按我的预期工作。也许我可以使用StepVerifier来达到此目的,但我只是不知道如何在我的情况下使用它。有什么有用的提示吗?
我认为您可以使用模拟网络服务器(例如MockWebServer )来测试它。
@Test
public void testReactiveWebClient() throws IOException
{
MockWebServer mockWebServer = new MockWebServer();
String expectedResponse = "expect that it works";
mockWebServer.enqueue(new MockResponse().setResponseCode(429));
mockWebServer.enqueue(new MockResponse().setResponseCode(429));
mockWebServer.enqueue(new MockResponse().setResponseCode(429));
mockWebServer.enqueue(new MockResponse().setResponseCode(200)
.setBody(expectedResponse));
mockWebServer.start();
HttpUrl url = mockWebServer.url("/mvuri");
WebClient webClient = WebClient.create();
Mono<String> responseMono = webClient.post()
.uri(url.uri())
.body(BodyInserters.fromObject("myRequest"))
.retrieve()
.onStatus(
httpStatus -> httpStatus.equals(HttpStatus.TOO_MANY_REQUESTS),
response -> Mono.error(new TestStuff.TooManyRequestsException("System is overloaded")))
.bodyToMono(String.class)
.retryWhen(Retry.anyOf(TestStuff.TooManyRequestsException.class)
.fixedBackoff(Duration.ofSeconds(1)).retryMax(3));
StepVerifier.create(responseMono)
.expectNext(expectedResponse)
.expectComplete().verify();
mockWebServer.shutdown();
}
Run Code Online (Sandbox Code Playgroud)
如果您MockResponse使用 statuscode将另一个队列入队429,则验证将失败,与例如 errorcode 相同500。
| 归档时间: |
|
| 查看次数: |
13206 次 |
| 最近记录: |