我正在使用Springs 的 Webclient 进行 HTTP GET 调用。
如何验证作为 HTTP 调用响应收到的响应对象 GetPersonBasicInfoResWrapper
的属性。
我试图通过阻止响应对象来验证 flatMap
内的 birthDate
,但它看起来并不是最实用的方法。
以下是我的代码摘录。
private Mono<GetPersonBasicInfoResWrapper> getPersonBasicInfo(Double personId, LocalDate birthDate,
CallerRequestMetaData callerInfo) {
return middlewareWebClient
.get()
.uri(...)
...
...
.exchange()
.flatMap(client -> {
GetPersonBasicInfoResWrapper block = client.bodyToMono(GetPersonBasicInfoResWrapper.class).block();
LocalDate personBirthDate = LocalDateTime.ofInstant(block.getBirthDate().toInstant(),ZoneId.of(Constants.DEFAULT_TIME_ZOME)).toLocalDate();
if (!personBirthDate.equals(birthDate))
throw new YakeenRowadException(Errors.INCORRECT_ID_BIRTH_DATE_G, birthDate.toString());
else
return client.bodyToMono(GetPersonBasicInfoResWrapper.class);
});
}
非常感谢任何帮助。
最佳答案
尝试这样的事情
private Mono<PersonInfo> getPersonInfo(Double personId) {
return webClient.get()
.uri(...)
.exchange()
.flatMap(response -> {
return response.bodyToMono(PersonInfo.class);
});
}
private LocalDate toLocalDate(Instant instant) {
return LocalDateTime.ofInstant(instant, ZoneId.of(Constants.DEFAULT_TIME_ZOME))
.toLocalDate();
}
public Mono<PersonInfo> doSomething(Double personId, LocalDate birthDate) {
return getPersonInfo(personId)
.flatMap(personInfo -> {
final LocalDate birthDate = toLocalDate(personInfo.getBirthDate().toInstant());
if (!personBirthDate.equals(birthDate)) {
return Mono.error(new YakeenRowadException(Errors.INCORRECT_ID_BIRTH_DATE_G, birthDate.toString()));
}
return Mono.just(personInfo);
});
}
在获取过程中不要验证,验证是业务逻辑,应该在上面的层中。
- 您获取并返回
- 您验证。
- 如果验证失败,您将向调用客户端返回 Mono.error()。
我不知道“元数据”应该是什么。我希望这不是 url,因为以这种方式传递它是错误的。
(尽量避免冗长的命名)
关于spring-boot - 如何在 Spring WebClient 中验证响应对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60925208/