Rest Template Vs Web Client

Since the REST era, most developers have become used to working with Spring’s traditional RestTemplate from the package spring-boot-starter-web for consuming Rest services. Spring also has a WebClient in its reactive package called spring-boot-starter-webflux.

Since WebClient is supposed to be the successor of RestTemplate, we will be looking into it a bit deeper.

RestTemplate provides a synchronous way of consuming Rest services, which means it will block the thread until it receives a response. RestTemplate is deprecated since Spring 5 which means it’s not really that future proof.

WebClient exists since Spring 5 and provides an asynchronous way of consuming Rest services, which means it operates in a non-blocking way. WebClient is in the reactive WebFlux library and thus it uses the reactive streams approach. However, to really benefit from this, the entire throughput should be reactive end-to-end. 

Another benefit of working with Flux and Mono is that you can do mappings, filtering, transformations on your data as it is passing through the stream.

public Flux<String> getRecipes() {

    Flux<Recipe> recipeStream = webClient.get().uri("/recipe").retrieve().bodyToFlux(Recipe.class);

    Flux<String> recipeTitleStream = recipeStream

            .log().filter(recipe -> !recipe.getTitle().isBlank())

            .flatMap(recipe -> Mono.just(recipe.getTitle().toUpperCase()));

    return recipeTitleStream;

}

We have learned that RestTemplate is in maintenance mode and probably will not be supported in future versions. Even on the official Spring documentation, they advise to use WebClient instead. WebClient can basically do what RestTemplate does, making synchronous blocking calls. But it also has asynchronous capabilities, which makes it interesting. It has a functional way of programming, which makes it easy to read as well. If you are working in legacy Spring (< 5.0) applications, you will have to upgrade to Spring 5.0 to be able to use WebClient.

Comments

Popular posts from this blog

Java 8 : Find the number starts with 1 from a list of integers

Optional Vs Null Check

How to prevent Singleton Class from Reflection and Serialization