代码之家  ›  专栏  ›  技术社区  ›  Hermes Chavez

如何将springboot rest端点转换为spring webflux反应端点

  •  0
  • Hermes Chavez  · 技术社区  · 2 年前

    bellow是我的代码,它是用springboot编写的,但我在尝试用webflux编写它时遇到了麻烦。我正在使用mono,但我不确定如何在mono中记录信息,或者如何使用mono返回响应。

    @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 ");
    
        }
    
    2 回复  |  直到 2 年前
        1
  •  0
  •   Ignacio Padilla    2 年前
    @GetMapping("/helloWorld")
    public Mono<ResponseEntity<String>> helloWorld() {
    
       log.info("Entered hello world");
    
       return Mono.just(ResponseEntity.ok("Hello World"));
    }
    

    可能建议阅读春季网络流量 docs 以及项目反应堆 docs .

    此外,如果您需要记录所有反应流,我建议您使用以下代码。

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

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

        2
  •  0
  •   Ofer Skulsky    2 年前

    函数应返回一个 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>