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

use*_*892 2 java spring-webflux

我刚刚开始使用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));
    }
}
Run Code Online (Sandbox Code Playgroud)

IntelliJ 给我警告,readValue()并且toURL()是线程阻塞方法调用。

我可以忽略这个还是我应该如何返回我从文件系统读取并映射到域类的 JSON 结构?

我觉得这应该以异步方式或至少更“被动”的方式完成。

Tho*_*olf 8

您应该将它包装在 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));

}
Run Code Online (Sandbox Code Playgroud)