簡體   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