실제 백엔드 솔루션 구축 시, 하나의 백엔드 앱이 다른 백엔드 앱이 노출한 엔드포인트를 호출해야 하는 경우가 빈번합니다. 이를 구현하기 위한 스프링의 주요 방법론을 정리했습니다.
OpenFeign은 인터페이스와 애너테이션 기반으로 동작하며, 개발자가 메서드를 직접 구현할 필요가 없다는 것이 가장 큰 장점입니다.
@EnableFeignClients를 사용하여 기능을 활성화하고 스캔할 위치를 지정합니다.@FeignClient(name = "payments", url = "${name.service.url}")
public interface PaymentsProxy {
@PostMapping("/payment")
Payment createPayment(
@RequestHeader String requestId,
@RequestBody Payment payment
);
}
@Configuration
@EnableFeignClients(basePackages = "com.example.spring_test.proxy")
public class ProjectConfig {
}
@RestController
public class PaymentsController {
private final PaymentsProxy paymentsProxy;
public PaymentsController(PaymentsProxy paymentsProxy) {
this.paymentsProxy = paymentsProxy;
}
@PostMapping("/payment")
public Payment payment(
@RequestBody Payment payment
){
String requestId = UUID.randomUUID().toString();
return paymentsProxy.createPayment(requestId,payment);
}
}
직접 HTTP 요청 구성 요소들을 인스턴스화하여 호출을 전송하고 응답을 수신하는 방식입니다.
RestTemplate 빈(Bean)을 직접 생성하거나 스캔 위치를 알려주어야 합니다.@Component
public class PaymentsProxy {
private final RestTemplate rest;
@Value("${name.service.url}")
private String paymentsServiceUrl;
public PaymentsProxy(RestTemplate rest) {
this.rest = rest;
}
public Payment createPayment(Payment payment){
String uri = paymentsServiceUrl + "/payment";
HttpHeaders headers = new HttpHeaders(); //1)
headers.add("requestId", UUID.randomUUID().toString());
HttpEntity<Payment> httpEntity = new HttpEntity<>(payment,headers); //2)
ResponseEntity<Payment> response = rest.exchange(uri, HttpMethod.POST,httpEntity,Payment.class);
//3)
return response.getBody();
}
}
@RestController
public class PaymentsController {
private final PaymentsProxy paymentsProxy;
public PaymentsController(PaymentsProxy paymentsProxy) {
this.paymentsProxy = paymentsProxy;
}
@PostMapping("/payment")
public Payment createPayment(
@RequestBody Payment payment
){
return paymentsProxy.createPayment(payment);
}
}
@Configuration
public class ProjectConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
#Spring #OpenFeign #RestTemplate #WebClient #API_Call #백엔드공부