SpringCloud - Feign Client

Neo-Renaissance·2025년 5월 25일

Feign Client란?

기존의 RestTemplate과 달리 인터페이스와 어노테이션만으로 REST 클라이언트를 구현할 수 있어 코드의 복잡성을 줄여줌.

💡 RestTemplate

  • HTTP 통신을 위한 도구로 다양한 HTTP 메서드(GET, POST, PUT, DELETE 등)을 지원하는 RESTful API 웹 서비스와의 상호작용을 쉽게 외부 도메인에서 데이터를 가져오거나 전송할 때 사용되는 스프링 프레임워크의 클래스를 의미함.

Feign의 가장 큰 특징은 선언적 REST 클라이언트로 개발자는 HTTP 요청을 보내고 응답을 처리하는 하위 부분의 세부 사항을 신경쓰지 않고 단순히 인터페이스에 어노테이션을 추가를 통해서 외부 RESTful 서비스를 쉽게 호출 가능.
-> Spring이 런타임에 인터페이스의 구현체를 자동으로 제공하므로, 개발자는 구현 로직을 작성할 필요가 없음.

RestTemplate vs Feign Client

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");
    }
}

Feign Client의 주요 장점

간결성과 가독성

  • RestTemplate: 15줄 이상의 복잡한 코드
  • Feign Client: 3줄의 간단한 인터페이스 정의

선언형 접근 방식

  • HTTP 요청을 인터페이스와 어노테이션으로 정의하여 코드의 의도가 명확함

Spring MVC 어노테이션 재사용

  • @GetMapping, @PostMapping, @PathVariable 등 기존 Spring 어노테이션을 그대로 사용 가능

유지보수성 향상

  • 인터페이스 기반으로 API 변경사항을 쉽게 반영할 수 있음
profile
if (실패) { 다시 도전; } else { 성공; }

0개의 댓글