Spring Boot Webflux:避免在处理程序中调用线程阻塞方法

时间:2019-12-06 18:55:09

标签: 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));
    }
}

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

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

我觉得应该以一种异步的方式,或者至少是“反应性地”完成。

1 个答案:

答案 0 :(得分:1)

您应该将其包装在fromCallable中,并确保它在自己的线程上运行。

Blocking calls in reactor

@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)
            .syncBody(foo));

}
相关问题