RestTemplate
- RestTemplate : 블로킹 I/O 기반 동기 API
- RestTemplateAutoConfiguration
- 프로젝트 spring-web 모듈 존재시 RestTemplateBuilder를 빈으로 등록함
WebClient
- 논 블로킹 I/O 기반 비동기 API
- WebClientAutoConfiguration
- 프로젝트 spring-webflux 모듈 존재시 WebClient.Builder 빈을 등록해 줌
결과 적으로 동기, 비동기에 따라
RestTemplateBuilder , WebClient.Builder 를 사용해서 객체를 빌딩하여 사용하게 된다. 빌더 패턴이므로 체인 api 도 존재함
@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(5000l);
return "world";
}
}
@Component
public class RestRunner implements ApplicationRunner {
@Autowired
private 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());
}
}
hello
world
StopWatch '': running time = 10241013100 ns
---------------------------------------------
ns % Task name
---------------------------------------------
10241013100 100%
@Component
public class NoneBlockingRestRunner implements ApplicationRunner {
@Autowired
private WebClient.Builder builder;
@Override
public void run(ApplicationArguments args) throws Exception {
WebClient webClient = builder.build();
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// stream api
Mono<String> helloMono = webClient.get().uri("http://localhost:8080/hello").retrieve().bodyToMono(String.class);
// stream 동작
helloMono.subscribe( s -> {
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( f -> {
System.out.println(f);
if(stopWatch.isRunning()) {
stopWatch.stop();
}
System.out.println(stopWatch.prettyPrint());
});
}
}
world
hello
StopWatch '': running time = 6557595600 ns
---------------------------------------------
ns % Task name
---------------------------------------------
6557595600 100%
StopWatch '': running time = 6557595600 ns
---------------------------------------------
ns % Task name
---------------------------------------------
6557595600 100%
'SpringBoot' 카테고리의 다른 글
Spring Boot Acutator (0) | 2020.11.08 |
---|---|
Rest 클라이언트 커스터마이징 (0) | 2020.11.08 |
MongoDB (0) | 2020.11.08 |
데이터베이스마이그레이션 (0) | 2020.11.08 |
JPA 사용시 데이터베이스 스키마 초기화 및 데이터 사용 방법 (0) | 2020.11.08 |