簡體   English   中英

我如何將 springboot 休息端點轉換為 spring webflux 反應端點

[英]How can i turn springboot rest endpoints to spring webflux reactive endpoints

下面是我的代碼,它是用springboot編寫的,但我在嘗試用webflux編寫它時遇到了麻煩。 我正在使用單聲道,但我不確定如何在單聲道中記錄信息或如何使用單聲道返回 responseEntity。

@GetMapping("/helloWorld")
public ResponseEntity helloWorld() {

    log.info("Entered hello world");

    return ResponseEntity.ok("Hello World");
}

我在 webflux 中所做的並不多,但這就是我能做到的

   @GetMapping("/helloWorld")
    public Mono<ResponseEntity> helloWorld() {
//        log.info("Entered hello world in controller");
        Mono<String> defaultMono = Mono.just("Entered hello world").log();
        defaultMono.log();
//        return ResponseEntity.ok("Hello World ");

    }

您的函數應返回Mono (單一資源)或Flux (集合資源)。

@GetMapping("/helloWorld")
public Mono<String> helloWorld() {

    log.info("Entered hello world");

    return Mono.just("Hello World");
}

您還應該確保您的依賴項中有spring-boot-starter-webflux

例如,maven pom:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
@GetMapping("/helloWorld")
public Mono<ResponseEntity<String>> helloWorld() {

   log.info("Entered hello world");

   return Mono.just(ResponseEntity.ok("Hello World"));
}

可能建議閱讀 spring webflux 文檔以及 Project Reactor文檔

此外,如果您需要記錄所有反應流,我建議您使用以下代碼。

@GetMapping("/helloWorld")
public Mono<ResponseEntity<String>> helloWorld() {       
    return Mono.just("Entered hello world in controller").log().map(s -> ResponseEntity.ok(s));
}

可以在 Internet 上找到一些不錯的 spring webflux 示例,例如: Building Async REST APIs with Spring WebFlux

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM