Java/Spring Boot

[Spring Boot] REST Client (RestTemplate과 WebClient)

hh_lin 2022. 5. 7. 15:37

1. REST Client

  • Spring Framework에서 제공
  • Spring Boot는 REST Client를 쉽게 사용할 수 있도록 빈을 등록해줌
    RestTemplate, WebClient 타입의 빈을 등록해주는 것이 아니라
    RestTemplateBuilder, WebClient.Builder를 빈으로 등록해줌

 

 

 

 

 

 

 

 

 

 

 

2. RestTemplate

 

 

 

# RestTemplateAutoConfiguration

-> RestTemplate이 classpath에 있으면 RestTemplateAutoConfiguration 자동 설정 사용

 

-> RestTemplateBuilder가 빈으로 등록되어 있는 것 확인 가능

 

 

 

 

# SampleController

@RestController
public class SampleController {

   @GetMapping("/hello")
   public String hello() throws InterruptedException {
      Thread.sleep(5000l);
      return "hello";
   }

   @GetMapping("/world")
   public String world() throws InterruptedException {
      Thread.sleep(3000l);
      return "world";
   }

}

 

 

 

# RestTemplate

@Component
public class RestRunner implements ApplicationRunner {

   @Autowired
   RestTemplateBuilder restTemplateBuilder;

   @Override
   public void run(ApplicationArguments args) throws Exception {

      RestTemplate restTemplate = restTemplateBuilder.build();

      StopWatch stopWatch = new StopWatch();
      stopWatch.start();

      // TODO /hello 호출
      // 원하는 응답의 타입을 지정해주면 해당 타입으로 바로 결과를 가져올 수 있음
      String helloResult = restTemplate.getForObject("http://localhost:8080/hello", String.class);
      System.out.println(helloResult);

      // TODO /world 호출
      String worldResult = restTemplate.getForObject("http://localhost:8080/world", String.class);
      System.out.println(worldResult);

      stopWatch.stop();
      System.out.println(stopWatch.prettyPrint());
   }
}

 

 

 

 

# 실행결과

-> 대략 8초 소요되는 것 확인 가능

 

 

 

 

 

 

 

 

 

 

 

 

 

3. WebClient

 

 

# WebClient

@Component
public class RestRunner implements ApplicationRunner {

	@Autowired
	WebClient.Builder builder;

	@Override
	public void run(ApplicationArguments args) throws Exception {

		WebClient webClient = WebClient.builder().build();

		StopWatch stopWatch = new StopWatch();
		stopWatch.start();

		Mono<String> helloMono = webClient.get().uri("http://localhost:8080/hello")
			.retrieve()
			.bodyToMono(String.class);

		// 실제 요청 보내고 응답 가져오는 부분
		// subscribe 자체는 Non-Blocking
		helloMono.subscribe(s -> {
			// 응답이 오면 callback으로 이 부분이 실행되는 것
			System.out.println(s);

			if (stopWatch.isRunning()) {
				stopWatch.stop();
			}

			System.out.println(stopWatch.prettyPrint());
			stopWatch.start();
		});

		Mono<String> worldMono = webClient.get().uri("http://localhost:8080/world")
			.retrieve()
			.bodyToMono(String.class);

		worldMono.subscribe(s -> {
			System.out.println(s);

			if (stopWatch.isRunning()) {
				stopWatch.stop();
			}

			System.out.println(stopWatch.prettyPrint());
			stopWatch.start();
		});
	}
}

 

 

 

# 실행결과

-> world가 먼저 출력되고 2초 정도 뒤에 hello 출력되는 것 확인 가능

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8/dashboard

 

스프링 부트 개념과 활용 - 인프런 | 강의

스프링 부트의 원리 및 여러 기능을 코딩을 통해 쉽게 이해하고 보다 적극적으로 사용할 수 있는 방법을 학습합니다., - 강의 소개 | 인프런...

www.inflearn.com