기존의 RestTemplate과 달리 인터페이스와 어노테이션만으로 REST 클라이언트를 구현할 수 있어 코드의 복잡성을 줄여줌.
💡 RestTemplate
- HTTP 통신을 위한 도구로 다양한 HTTP 메서드(GET, POST, PUT, DELETE 등)을 지원하는 RESTful API 웹 서비스와의 상호작용을 쉽게 외부 도메인에서 데이터를 가져오거나 전송할 때 사용되는 스프링 프레임워크의 클래스를 의미함.
Feign의 가장 큰 특징은 선언적 REST 클라이언트로 개발자는 HTTP 요청을 보내고 응답을 처리하는 하위 부분의 세부 사항을 신경쓰지 않고 단순히 인터페이스에 어노테이션을 추가를 통해서 외부 RESTful 서비스를 쉽게 호출 가능.
-> Spring이 런타임에 인터페이스의 구현체를 자동으로 제공하므로, 개발자는 구현 로직을 작성할 필요가 없음.
RestTemplate과 Feign Client의 간단한 비교를 통해 Feign Client의 장점을 비교해보자
외부 API에서 사용자 정보를 조회하는 예시
RestTemplate 방식
@Service
public class UserService {
public UserDto getUser(Long userId) {
RestTemplate restTemplate = new RestTemplate();
// 헤더 설정
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer token");
headers.setContentType(MediaType.APPLICATION_JSON);
// URI 구성
URI uri = UriComponentsBuilder
.fromUriString("https://api.example.com")
.path("/users/{userId}")
.buildAndExpand(userId)
.toUri();
// HTTP 요청 실행
HttpEntity entity = new HttpEntity<>(headers);
ResponseEntity response = restTemplate.exchange(
uri,
HttpMethod.GET,
entity,
UserDto.class
);
return response.getBody();
}
}
Feign Client 방식
@FeignClient(name = "userClient", url = "https://api.example.com")
public interface UserClient {
@GetMapping("/users/{userId}")
UserDto getUser(@PathVariable("userId") Long userId,
@RequestHeader("Authorization") String token);
}
@Service
public class UserService {
@Autowired
private UserClient userClient;
public UserDto getUser(Long userId) {
return userClient.getUser(userId, "Bearer token");
}
}
간결성과 가독성
선언형 접근 방식
Spring MVC 어노테이션 재사용
@GetMapping, @PostMapping, @PathVariable 등 기존 Spring 어노테이션을 그대로 사용 가능유지보수성 향상