1. Spring Cloud OpenFeign이란?
1.1 개념과 등장 배경
- Spring Cloud OpenFeign은 Netflix에서 개발한 Feign을 Spring Cloud 생태계에 통합한 선언적 HTTP 클라이언트 라이브러리입니다.
- 기존의 RestTemplate이나 WebClient를 사용할 때 발생하는 반복적인 코드 작성과 복잡한 설정을 해결하기 위해 등장했습니다.
- 인터페이스와 어노테이션만으로 HTTP API를 호출할 수 있어, 마치 로컬 메서드를 호출하는 것처럼 간단하게 외부 서비스와 통신할 수 있습니다.
1.1.1 기존 방식의 문제점
// RestTemplate을 사용한 기존 방식
@Service
public class UserService {
private final RestTemplate restTemplate;
public User getUser(Long userId) {
String url = "http://user-service/users/" + userId;
try {
ResponseEntity<User> response = restTemplate.getForEntity(url, User.class);
if (response.getStatusCode().is2xxSuccessful()) {
return response.getBody();
}
throw new UserNotFoundException("User not found");
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
throw new UserNotFoundException("User not found");
}
throw new ServiceException("Failed to get user", e);
}
}
}
- 위 코드의 문제점은 다음과 같습니다.
- URL 구성, 예외 처리, 응답 검증 등 비즈니스 로직과 무관한 코드가 많습니다.
- 동일한 패턴의 코드가 API 호출마다 반복됩니다.
- 타입 안정성이 떨어지고 리팩토링이 어렵습니다.