Home > OS >  How can i turn springboot rest endpoints to spring webflux reactive endpoints
How can i turn springboot rest endpoints to spring webflux reactive endpoints

Time:07-01

bellow is my code, its written in springboot but im having trouble trying to write it in webflux. im using mono but im not sure how i can log info in mono or how i can return a responseEntity using mono either.

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

    log.info("Entered hello world");

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

there is not much i did in webflux but this is how far i got

   @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 ");

    }

CodePudding user response:

Your function should return a Mono (single resource) or a Flux (collection resource).

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

    log.info("Entered hello world");

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

You should also make sure you have spring-boot-starter-webflux in your dependencies.

for example, maven pom:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

CodePudding user response:

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

   log.info("Entered hello world");

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

May suggest reading the spring webflux docs as well Project Reactor docs.

Also if what you need is to log all the reactive stream I'd would suggest following code.

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

Some good spring webflux example can be found on internet, such: Building Async REST APIs with Spring WebFlux

  • Related