Reactive Java with Spring WebFlux and Reactor

Learn extra at:

Utilizing the reactive HTTP consumer

Now, let’s make an endpoint that accepts an ID parameter. We’ll use the Spring reactive HTTP consumer and An API of Ice and Fire to make a request for a Sport of Thrones character primarily based on ID. Then, we’ll ship the character knowledge again to the person. Discover the brand new apiChain() methodology and its imports right here:


import org.springframework.internet.reactive.perform.consumer.WebClient;

@GetMapping("character/{id}")
  public Mono<String> getCharacterData(@PathVariable String id) {
    WebClient consumer = WebClient.create("https://anapioficeandfire.com/api/characters/");
    return consumer.get()
      .uri("/{id}", id)
      .retrieve()
      .bodyToMono(String.class)
      .map(response -> "Character knowledge: " + response);
  }

In the event you navigate to localhost:8080/character/148, you’ll get the biographical info for who is clearly the most effective character in The Sport of Thrones.

This instance works by accepting the ID path parameter and utilizing it to make a request to the WebClient class. On this case, we’re creating an occasion for our request, however you’ll be able to create a WebClient with a base URL after which reuse it repeatedly with many paths. We put the ID into the trail after which name retrieve adopted by bodyToMono(), which transforms the response right into a Mono. Do not forget that all this stays nonblocking and asynchronous, so the code that waits for the response from the API is not going to block the thread. Lastly, we use map() to formulate a response again to the person.

Turn leads into sales with free email marketing tools (en)

Leave a reply

Please enter your comment!
Please enter your name here