
RestTemplate, WebClient [1] 동기 방식
- 요청 보낸 후 응답(=결과)를 받아야 다음 동작이 이루어지는 방식
- Action -> Reaction -> Next Step
(⇔) 비동기 방식
- 요청 보낸 후 결과와 상관없이 다음 동작이 이루어지는 방식
- Action -> (Next Step) -> Reaction
잘 정리된 사이트인 이곳을 참고하도록 하자
클라이언트로부터 요청을 받는 컨트롤러, RestTemplate 활용해 다른 서버에 통신 요청하는 서비스 계층으로 작성

서버 간 통신 도식화
- 앞서 생성한 서버 프로젝트에 요청 날리기 위해 서버의 역할 수행하며 다른 서버로 요청 보내는 클라이언트의 역할도 수행하는 프로젝트 생성
@Service
public class RestTemplateService{
public String getName(){ //
URI uri = UriComponentsBuilder
.fromUriString("http://localhost:8888")
.path("/api/v1/curd-api")
.encode()
.build()
.toUri();
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
return response.getBody();
}
...
...
}
```java
UriComponentsBuilder
.expend("Flature")
or
UriComponentsBuilder
.queryParam("name", "Flature")
```@RestController
@RequestMapping("/rest")
@RequiredArgsConstructor
public class RestTemplateController{
private final RestTemplateService service;
@GetMapping
public String getName(){
return restTemplateService.getName();
}
...
@PostMapping
public ResponseEntity<MemberDTO> postDto(){
return restTemplateService.postWithParamAndBody();
}
}
WebClient 생성 방법
WebClient 생성
@Service
public class WebClientService{
// builder() 활용
public String getName(){
WebClient wc = WebClient.builder()
.baseUrl("http://localhost:8080")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MedidType.APPLICATION_JSON_VALUE)
.build();
return wc.get()
.uri("/api/v1/get-api")
.retrieve()
.bodyToMono(String.class)
.block();
}
// create() 활용
public String getNameWithPathVariable(){
WebClient wc = WebClient.create("http://localhost:8080");
ResponseEntity<String> responseEntity = wc.get()
.uri(uriBuilder -> uriBuilder.path("/api/v1/get-api/{name}"))
.build("Flature")
.retrieve().toEntity(String.class).block();
return responseEntity.getBody();
}
}