首页 > 解决方案 > spring boot 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));
    }
}

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

我可以忽略这一点,或者我应该如何返回从文件系统读取并映射到域类的 JSON 结构?

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

标签: javaspring-webflux

解决方案


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

}

推荐阅读