Spring WebClient vs. RestTemplate

1 Introduction

In this tutorial, we will be comparison of the two Web client implementations Spring - RestTemplate and Spring 5 in New Reactive alternative WebClient .

2. Blocking vs non-blocking client

Web applications, HTTP calls to other services is a very common requirement. Therefore, we need a Web client tools.

2.1. RestTemplate blocking client

For a long time, Spring has been providing RestTemplate as a Web client abstraction. At the bottom, RestTemplate model uses one thread (thread-per-request) based on the request of each Java Servlet API.

This means that, before the Web client until a response is received, the thread would have blocked it. The problem is caused by obstruction of code, each thread consumes a certain amount of memory and CPU cycles.

Let us have a lot of incoming requests under consideration, they are waiting for slow service produce some desired result.

Waiting for the results of requests piled up sooner or later. Therefore, the program will create a lot of threads that will run out of thread pool or take up all available memory. Due to frequent CPU context (thread) switching, we also experience performance degradation.

2.2. WebClient non-blocking client

On the other hand, WebClient using asynchronous Spring Reactive Framework provided by a non-blocking solution.

When RestTemplate for each event (HTTP request) to create a new thread when, WebClient will create a similar "mission" stuff each event. Behind the scenes, Reactive frame will these "tasks" queue, and execute them only when the proper response is available.

Reactive framework uses an event-driven architecture. It is provided by Reactive Streams API method of combining asynchronous logic. Therefore, as compared with the synchronous / blocking method, Reactive threads and using less system resources to handle more logic.

WebClient is Spring WebFlux part of the library. Thus, we can also use smooth function API for writing client code, and as a statement in response to the type of composition (Mono and Flux).

3. Comparative Cases

To demonstrate the difference between the two methods, we need to use a lot of concurrent client requests to run performance tests. After Yidingshuliang concurrent requests, we will see a significant decline blocking method performance.

On the other hand, regardless of the number of requests, reactive / non-blocking method can provide a constant performance.

For this article, let us realize two REST endpoints, use a RestTemplate, the other using WebClient. Their task is to call another slow response REST Web service that returns a Tweet List.

First, we need to introduce Spring Boot WebFlux starter dependent on :

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

Next, this is our slow service REST endpoints:

@GetMapping("/slow-service-tweets")
private List<Tweet> getAllTweets() {
    Thread.sleep(2000L); // delay
    return Arrays.asList(
      new Tweet("RestTemplate rules", "@user1"),
      new Tweet("WebClient is better", "@user2"),
      new Tweet("OK, both are useful", "@user1"));
}

3.1 Use RestTemplate call the slow service

Now, let's implement another REST endpoints, through the Web client will call our slow server.

First, let's use RestTemplate :

@GetMapping("/tweets-blocking")
public List<Tweet> getTweetsBlocking() {
    log.info("Starting BLOCKING Controller!");
    final String uri = getSlowServiceUri();

    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<List<Tweet>> response = restTemplate.exchange(
      uri, HttpMethod.GET, null,
      new ParameterizedTypeReference<List<Tweet>>(){});

    List<Tweet> result = response.getBody();
    result.forEach(tweet -> log.info(tweet.toString()));
    log.info("Exiting BLOCKING Controller!");
    return result;
}

When we call this endpoint, because the RestTemplate synchronous nature of the code will block waiting for a response from the slow service. Only when the response is received, it will perform the rest of the code in this method. Through the log, we can see:

Starting BLOCKING Controller!
Tweet(text=RestTemplate rules, username=@user1)
Tweet(text=WebClient is better, username=@user2)
Tweet(text=OK, both are useful, username=@user1)
Exiting BLOCKING Controller!

3.2 Use WebClient call the slow service

Secondly, let us use WebClient to call the slow service:

@GetMapping(value = "/tweets-non-blocking", 
            produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Tweet> getTweetsNonBlocking() {
    log.info("Starting NON-BLOCKING Controller!");
    Flux<Tweet> tweetFlux = WebClient.create()
      .get()
      .uri(getSlowServiceUri())
      .retrieve()
      .bodyToFlux(Tweet.class);

    tweetFlux.subscribe(tweet -> log.info(tweet.toString()));
    log.info("Exiting NON-BLOCKING Controller!");
    return tweetFlux;
}

In the present embodiment, the WebClient returns a Flux performed after completion of the method of the producer. Once the results are available, the publisher will start sending tweets to its subscribers. Note that calling / tweets-non-blocking of this endpoint client (Web browser in this example) would also subscribe to the return of Flux object.

Let us observe this log:

Starting NON-BLOCKING Controller!
Exiting NON-BLOCKING Controller!
Tweet(text=RestTemplate rules, username=@user1)
Tweet(text=WebClient is better, username=@user2)
Tweet(text=OK, both are useful, username=@user1)

Note that the method for this endpoint were completed before a response is received.

4 Conclusion

In this paper, we explore two different ways using the Web client in Spring.

RestTemplate using the Java Servlet API, synchronization and is therefore blocked. Instead, WebClient is asynchronous, while waiting for a response is returned without blocking the executing thread. Only when the program is ready, it will generate a notification.

RestTemplate will still be used. However, in some cases, compared with the blocking method, system resources, non-blocking methods used much less. Therefore, in these cases, WebClient after all, is a better choice.

All code snippets mentioned in the text, are available at GitHub found on.

Original: https://www.baeldung.com/spring-webclient-resttemplate

Author: Drazen Nikolic

Translator: Wan think ------

Welfare friends - will soon send the translated article before finishing became a PDF. No background in public reply: oh 002 can receive follow-up will continue to update the contents of a PDF, so stay tuned!



img

Guess you like

Origin www.cnblogs.com/liululee/p/11275427.html