MSA/Spring
[Spring Boot]WebClient를 이용한 POST 통신
길성이
2020. 2. 26. 23:55
1. WebClient 란?
Web request를 수행하기 위한 entry point를 표현하기 위한 인터페이스.
Spring Web Reactive 모듈의 한 파트로 생겨났음.
RestTemplate이 곧 deprecated 되기 때문에 WebClient 사용에 익숙해지길 권고함
2. Dependency in Maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
3. 예제 구조
WebMain에서 API 서버에 GetUserInfo라는 메서드에 EmpInfo라는 Body를 포함하 POST 요청을 보내면 보낸 EmpInfo를 그대로 Response해주는 간단한 구조
4. Client Side(WebMain)
@RestController
public class UserInfoController {
@Autowired
private EmpInfoService empInfoService;
@GetMapping("/empinfo")
public String getEmpInfo() {
EmpInfo result = empInfoService.getEmpInfo();
return "" + result.getId().toString() + " " + result.getDomain();
}
}
@Service("empInfoService")
public class EmpInfoService {
private WebClient webClient = WebClient.builder()
.baseUrl("http://localhost:7077")
.build();
public EmpInfo getEmpInfo() {
EmpInfo bodyEmpInfo = new EmpInfo();
bodyEmpInfo.setId(777);
bodyEmpInfo.setDomain("Jackpot");
return webClient.post() // POST method
.uri("/api/getUserInfo") // baseUrl 이후 uri
.bodyValue(bodyEmpInfo) // set body value
.retrieve() // client message 전송
.bodyToMono(EmpInfo.class) // body type : EmpInfo
.block(); // await
}
}
5. Server Side(API)
@RestController
@RequestMapping("/api")
public class UserInfoController {
@PostMapping(value = "/getUserInfo")
public EmpInfo getUserInfo(@RequestBody EmpInfo empInfo) {
return empInfo;
}
}
Reference
1. Spring 5 WebClient, baeldung, February 12, 2020, https://www.baeldung.com/spring-5-webclient