HomeCloud ComputingReactive Java with Spring WebFlux and Reactor

Reactive Java with Spring WebFlux and Reactor



Utilizing the reactive HTTP shopper

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


import org.springframework.internet.reactive.operate.shopper.WebClient;

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

If you happen to navigate to localhost:8080/character/148, you’ll get the biographical data for who is clearly one of the best character in The Recreation 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 possibly can 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. Keep in mind 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 consumer.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments