Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Using WebClient synchronously in Spring Web MVC stack

Sign upSign InSign upSign InMember-only storySaeed ZarinfamFollowITNEXT--ShareWebClient was introduced in Spring Framework 5, and the goal was to replace it with RestTemplate (Spring’s RestTemplate, which is now in maintenance mode).In this story, we want to answer these questions: Can WebClient be used in a Spring Project that uses the Web MVC stack? If so, how? and what are the consequences when we block the WebClient to get the result? And finally, what is the best configuration in this scenario?Yes, and the Spring team encourages us to do this. Suppose we add both spring-boot-starter-web and spring-boot-starter-webflux libraries dependencies in our build file. In that case, the Spring Boot auto-configuring will prioritize Spring MVC over WebFlux, allowing us to use WebClient in our Spring MVC project to make asynchronous HTTP requests to external services or APIs.WebClient is a non-blocking, reactive web client. It returns reactive data types from Project Reactor (Mono or Flux). When we use WebClient in a Spring Boot Web MVC project, we need to call the block() method from the Reactor data types (Mono or Flux). By calling the block() method, we block the current thread and retrieve data synchronously, but the WebClient performs an asynchronous, non-blocking call to the external service. Take a look at this simple code example:----ITNEXTA lifelong Learner, Lazy technical blogger ✍️ Late bloomer 🐌 Football lover ⚽️ Old Programmer 👨‍💻, My technical tweets: https://twitter.com/zarinfamSaeed Zarinfam--1Jacob FerusinITNEXT--8Mahdi MallakiinITNEXT--1Saeed ZarinfaminITNEXT--Alexander Obregon--1Aditya Gupta--Anurag RanainNaukri Engineering--5Pushkar Kumar--1Prerana KulawadeinJavarevisited--The Java Trail--HelpStatusAboutCareersBlogPrivacyTermsText to speechTeams



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

Using WebClient synchronously in Spring Web MVC stack

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×