์ธ๋ถAPI์ ์ฐ๋ํ ๋ ์ฌ์ฉํ๋ RestTemplate๊ณผ WebClient ๊ฐ์ ์ด๋ค ์ฐจ์ด๊ฐ ์์์ง ์ฐพ์๋ณด๊ณ , ์ด๋ค ๊ธฐ์ ์ ํ๋ก์ ํธ์ ์ฌ์ฉํ ์ง ๊ณ ๋ฏผํด๋ดค์ต๋๋ค.
Webflux ?
๋น๋๊ธฐ(Async), ๋ ผ๋ธ๋กํน(Non-blocking) ๋ฐฉ์์ ๋ฆฌ์กํฐ๋ธ ํ๋ก๊ทธ๋๋ฐ์ ์ง์ํ๋ ์คํ๋ง ํ๋ ์์ํฌ์ ๋ชจ๋์ ๋๋ค.
WebClient
Spring WebFlux์์ ์ ๊ณตํ๋ HTTP ์์ฒญ์ ๋ณด๋ด๊ธฐ ์ํด ์ฌ์ฉํ๋ ์ธํฐํ์ด์ค์ ๋๋ค.
RestTemplate ?
๋ธ๋กํน(Blocking) ๊ธฐ๋ฐ์ ๋๊ธฐ ๋ฐฉ์์ Spring MVC์ HTTP ํด๋ผ์ด์ธํธ์ ๋๋ค.
๊ทธ๋ ๊ธฐ ๋๋ฌธ์ ์ค๋ ๋๊ฐ ๋ค ์ฐจ์๋ ๊ฒฝ์ฐ Queue์์ ๋๊ธฐ๋ฅผ ํ๊ฒ๋์ด ์์ฒญ์ด ๋ง์์ง๊ฒ ๋๋ฉด ๋ณ๋ชฉ ํ์์ด ๋ํ๋ ์ ์์ต๋๋ค. ์ด๋ ์๋น์ค ์ฑ๋ฅ ์ ํ๋ก ์ฐ๊ฒฐ๋ ๊ฒ์ ๋๋ค.
WebClient VS RestTemplate ๋น๊ตํด๋ณด๊ธฐ
ํ๋์ ๋น์ฆ๋์ค ๋ก์ง ๋ด์์ ๋จ์ผ API ์์ฒญ๋ง ์ด๋ฃจ์ด์ง๋ ์ํฉ (์์ฒญ ์๊ฐ ์ ์ ์ํฉ)์์๋ RestTemplate๊ณผ WebClient์ ์ฐจ์ด๊ฐ ๋ฏธ๋ฏธํฉ๋๋ค.
ํ์ฌ ํ๋ก์ ํธ์์๋ ๋ง์ ์์ ์์ฒญ์ ๋ณด๋ด์ง๋ ์์ง๋ง ์๋์ ๊ฐ์ ์ด์ ๋ก ๊ฒฐ๋ก ์ ๋ด๋ฆฌ๊ฒ ๋์์ต๋๋ค.
- WebClient ์ฝ๋๋ ๊ฐ๋ ์ฑ์ด ์ข์ต๋๋ค.
- RestTemplate์ ํ์ฌ ์ ์ง๊ด๋ฆฌ ๋ชจ๋์ ์์ผ๋ฉฐ Spring์์ WebClient๋ฅผ ๊ถ์ฅํ๊ณ ์์ต๋๋ค.
- ์๋น์ค ํ์ฅ์ฑ๊ณผ MSA ์ ํ์ ๊ณ ๋ คํ์ฌ ์ค๊ณํ๊ธฐ๋ก ํ์ผ๋ฏ๋ก ์ถํ์ ๋๊ท๋ชจ ์์ฒญ์ ์ฌ์ฉํ ๊ฒ์ ๋๋นํ์ฌ webClient ๋ฅผ ์ฑํํ์์ต๋๋ค.
- ์ถํ reactive web ์ผ๋ก ์ ํ๋๋ค๋ฉด, ํด๋น ํด๋ผ์ด์ธํธ์์ ๋น๋๊ธฐ, ๋ ผ๋ธ๋กํน ๋ฐฉ์์ผ๋ก ๊ฐ๋จํ ๋ณ๊ฒฝ์ด ๊ฐ๋ฅํ ๊ฒ์ ๋๋ค.
RestTemplate ์์ ์ฝ๋
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.put(HttpHeaders.ACCEPT, Collections.singletonList(MediaType.APPLICATION_JSON_VALUE));
HttpEntity<String> entity = new HttpEntity<>(headers);
String result = restTemplate.exchange("https://example.com", HttpMethod.GET, entity, String.class).getBody();
*์ถ์ฒ: https://poalim.tistory.com/59*
WebClient ์ฝ๋
GeminiResponseDto aiAnswer = webClient.post()
.uri(geminiApiUrl + geminiApiKey)
.header("Content-Type", "application/json")
.bodyValue(requestBody)
.retrieve()
.bodyToMono(GeminiResponseDto.class)
.block();
RestClient์ ๋ฑ์ฅ
WebClient๋ ์์ ๋งํ ์ฅ์ ์ ๊ฐ์ง๊ณ ์์ง๋ง, Spring MVC ๊ฐ๋ฐ ํ๊ฒฝ์๋ ๋ง์ง ์์ต๋๋ค. ํ๊ฒฝ์ ๋ง๊ฒ ์ฌ์ฉํด์ฃผ๊ธฐ ์ํด์๋ .block()
์ผ๋ก ๋๊ธฐ ์ฒ๋ฆฌ๋ฅผ ํด์ฃผ์ด์ผ ํ์ต๋๋ค.
๋ํ, WebFlux ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ฌ์ฉํ๊ธฐ ์ํ spring-webflux
์์กด์ฑ ์ถ๊ฐ๊ฐ ํ์ํฉ๋๋ค.
RestClient
RestClient๋ ๋๊ธฐ์ HTTP Client์ ๋๋ค.
webflux์ ๋นํด ๋ค๋ฆ๊ฒ ๋ฐ๊ฒฌํ์ฌ ๋ฆฌํฉํ ๋ง์ ์งํํ์ต๋๋ค.
webflux๋ณด๋ค Spring MVC ๊ฐ๋ฐ ํ๊ฒฝ์ ์ ํฉํฉ๋๋ค. webFlux์ ๋ฌ๋ฆฌ ์์กด์ฑ์ ๋ฃ์ง ์์๋ ๋ฉ๋๋ค.
RestClient ์ฝ๋
ResponseEntity<GeminiResponseDto> aiAnswer = restClient.post()
.uri(geminiApiUrl + geminiApiKey)
.contentType(APPLICATION_JSON)
.body(requestBody)
.retrieve()
.toEntity(GeminiResponseDto.class);
์ฐธ๊ณ : https://docs.spring.io/spring-framework/reference/integration/rest-clients.html