Switching from RestTemplate to WebClient
RestTemplate will be deprecated in a future version(> 5.0) and will not have major new features added going forward.
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.
Now, let’s move on to some example basic methods we can use on the RestTemplate class to communicate with our Rest service. We apply CRUD operations, specify our return object’s class, some parameters, body, header, etc.
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.
Now, let’s move on to some example basic methods we can use on the WebClient class to communicate with our Rest service.
Here is an example similar to our RestTemplate example. Note that this wraps our objects in Mono (a stream of 0 or 1 object) and Flux (a stream of 0 or multiple objects) wrappers. These are reactive types, and we should keep them in these wrappers if we want to keep the reactive stream open and non-blocking.
As you can notice the example is for service that is not reactive.
Since our Rest service doesn’t provide reactive streams, we receive a List in one response, which WebClient wraps in Mono. We use block() to block the stream and get the data out of it. Note that this shouldn’t be used in a reactive environment.
Comments
Post a Comment