[英]spring boot webflux: avoid thread-blocking method calls in handler
我刚刚开始使用WebFlux
和整个反应式范式,我坚持这一点:
@Component
public class AbcHandler {
private ObjectMapper objectMapper = new ObjectMapper();
public Mono<ServerResponse> returnValue() throws IOException {
Abc abc = objectMapper.readValue(new ClassPathResource("data/abc.json").getURL(), Abc.class);
return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(abc));
}
}
IntelliJ 警告我readValue()
和toURL()
是线程阻塞方法调用。
我可以忽略这个还是我应该如何返回我从文件系统读取并映射到域类的 JSON 结构?
我觉得这应该以异步方式或至少更“被动”的方式完成。
您应该将它包装在 fromCallable 中,并确保它在自己的线程上运行。
@Autowire
private ObjectMapper objectMapper;
public Mono<ServerResponse> fooBar() throws IOException {
return Mono.fromCallable(() -> objectMapper.readValue(new ClassPathResource("data/Foo.json")
.getURL(), Foo.class))
.subscribeOn(Schedulers.boundedElastic())
.flatMap(foo -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
.bodyValue(foo));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.