์คํ๋ง์์ ์ง์ํ๋ ๊ฐ์ฒด๋ก, ๊ฐํธํ๊ฒ Rest ๋ฐฉ์ API๋ฅผ ํธ์ถํ ์ ์๋ ์คํ๋ง ๋ด์ฅ ํด๋์ค๋ค.
์คํ๋ง 3.0๋ถํฐ ์ง์ํ์๊ณ , json, xml ์๋ต์ ๋ชจ๋ ๋ฐ์ ์ ์๋ค.
ํน์ง
- Blocking I/O ๊ธฐ๋ฐ์ ๋๊ธฐ๋ฐฉ์์ ์ฌ์ฉํ๋ ํ ํ๋ฆฟ
- RESTful ํ์์ ๋ง์ถ์ด์ง ํ ํ๋ฆฟ
- Header, Content-Type ๋ฑ์ ์ค์ ํ์ฌ ์ธ๋ถ API ํธ์ถ
- Server to Server ํต์ ์ ์ฌ์ฉ
๋์์๋ฆฌ
- ์ ํ๋ฆฌ์ผ์ด์ ๋ด๋ถ์์ REST API์ ์์ฒญํ๊ธฐ ์ํด RestTemplate์ ๋ฉ์๋๋ฅผ ํธ์ถํ๋ค.
- RestTemplate์ MessageConverter๋ฅผ ์ด์ฉํด java object๋ฅผ request body์ ๋ด์ message(JSON etc.)๋ก ๋ณํํ๋ค. ๋ฉ์์ง ํํ๋ ์ํฉ์ ๋ฐ๋ผ ๋ค๋ฆ
- ClientHttpRequestFactory์์ ClientHttpRequest์ ๋ฐ์์ ์์ฒญ์ ์ ๋ฌํ๋ค.
- ์ค์ง์ ์ผ๋ก ClientHttpRequest๊ฐ HTTP ํต์ ์ผ๋ก ์์ฒญ์ ์ํํ๋ค.
- RestTemplate์ด ์๋ฌํธ๋ค๋ง์ ํ๋ค.
- ClientHttpResponse์์ ์๋ต ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ ์ค๋ฅ๊ฐ ์์ผ๋ฉด ์ฒ๋ฆฌํ๋ค.
- MessageConverter๋ฅผ ์ด์ฉํด response body์ message๋ฅผ java object๋ก ๋ณํํ๋ค.
- ๊ฒฐ๊ณผ๋ฅผ ์ ํ๋ฆฌ์ผ์ด์ ์ ๋๋ ค์ค๋ค.
API ํด๋์ค/๋ฉ์๋ ์ข ๋ฅ
ํด๋์ค
- RestTemplate : Spring 3๋ถํฐ ์ง์ํ์๊ณ , API ํธ์ถ ์ดํ ์๋ต์ ๋ฐ์ ๋๊น์ง ๊ธฐ๋ค๋ฆฌ๋ ๋๊ธฐ๋ฐฉ์
- AsyncRestTemplate : spring 4์ ์ถ๊ฐ๋ ๋น๋๊ธฐ RestTemplate. spring 5์์๋ deprecated ๋จ.
- WebClient : spring 5์์ ์ถ๊ฐ๋ ๋ ผ๋ธ๋ญ, ๋ฆฌ์กํฐ๋ธ ์น ํด๋ผ์ด์ธํธ๋ก ๋๊ธฐ, ๋น๋๊ธฐ ๋ฐฉ์์ ์ง์ํจ
๋ฉ์๋

์ฌ์ฉ์์
@Component
public class sendData {
private static RestTemplate restTemplate;
public static ResponseEntity<SubmitData> sendEngine() {
int SubNum = 123;
int Pnum = 1;
Object Pcode = "์ฝ๋";
SubmitData requestDto = SubmitData.builder()
.SubNum(SubNum)
.Pnum(Pnum)
.Pcode(Pcode)
.build();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
HttpEntity<SubmitData> entity = new HttpEntity<>(requestDto, headers);
String url = "http://localhost:8080/send";
return restTemplate.exchange(url, HttpMethod.POST, entity, SubmitData.class);
}
}