Spring WebClient


Spring WebClient

  • Spring WebClient supports Asynchronous non-blocking HTTP requests with functional coding style.
  • WebClient is part of a reactive web framework.
  • To use a reactive framework, we need to include spring-webflux module.
  • WebClient returns either Mono or Flux. (Will discuss later on these topics)

Controller

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import reactor.core.publisher.Mono;

@Controller
public class MyController {

	@Autowired
	private UserService userService;

	@GetMapping("/getUser/{userId}")
	@ResponseBody
	public Mono<Object> getUser(@PathVariable("userId") int userId) throws Exception {
		return userService.getUser(userId);
	}

}

Service

package com.example.demo;

import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import reactor.core.publisher.Mono;

@Service
public class UserService {

	public Mono<Object> getUser(int userId) throws Exception {
		WebClient webClient = WebClient.create("https://jsonplaceholder.typicode.com/todos/" + userId);
		return webClient.get().retrieve().bodyToMono(Object.class);
	}
}

App

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootExamplesApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootExamplesApplication.class, args);
	}

}

Gradle

plugins {
	id 'org.springframework.boot' version '2.1.7.RELEASE'
	id 'java'
}

apply plugin: 'io.spring.dependency-management'

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'org.springframework.boot:spring-boot-starter-webflux'	
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}