繁体   English   中英

spring boot webflux:避免处理程序中的线程阻塞方法调用

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM