- [Backend] Feign2025년 03월 26일
- 아몬드맛빼빼로
- 작성자
- 2025.03.26.:41
반응형
Feign!
Netflix에서 제공하는 API 클라이언트 라이브러리로 서버 단에서 외부 API 요청을 편리하게 하는 것이 목적인 라이브러리이다.
특징
- 선언형 인터페이스와 어노테이션만으로 REST API를 요청할 수 있다
- 복잡한 코드 없이 메서드처럼 간단히 외부 API를 요청할 수 있다
- @FeignClient를 이용하여 Spring Cloud 환경에서 쉽게 서비스 간 통신이 가능하다
- Ribbon, Hystrix 등과 통합되 로드 밸런싱,장애 처리 등의 기능과도 동시 사용이 가능한다
RestTemplate vs Feign
GET http://localhost:8081/users/{id}이러한 URL로 HTTP 요청을 전송하는 코드를 RestTemplate과 Feign를 이용하여 구현했을때 각각 어떤 차이가 있는지 알아보겠다.
Feign
1. 의존성 추가
dependencies { implementation 'org.springframework.cloud:spring-cloud-starter-openfeign' }2. 애플리케이션 설정
@SpringBootApplication @EnableFeignClients public class MyApplication { }3. Feign Client 인터페이스 정의
@FeignClient(name = "userClient", url = "http://localhost:8081") public interface UserClient { @GetMapping("/users/{id}") UserResponse getUserById(@PathVariable("id") Long id); }4. 비즈니스 로직에서 사용
@Service @RequiredArgsConstructor public class UserService { private final UserClient userClient; public UserResponse getUser(Long id) { return userClient.getUserById(id); } }RestTemplate
1. Bean 등록
@Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }2. 비즈니스 로직에서 사용
@Service @RequiredArgsConstructor public class UserService { private final RestTemplate restTemplate; public UserResponse getUser(Long id) { String url = "http://localhost:8081/users/" + id; return restTemplate.getForObject(url, UserResponse.class); } }비교
항목 Feign RestTemplate 선언 방식 @FeignClient 인터페이스 직접 URL 조합 및 호출 메서드 사용 코드 간결성 간결(메서드처럼 호출) URL과 매핑 직접 작성 설정 @EnableFeignClients 필요 RestTemplate 빈 등록 필요 유지보수 API 변화에 대응 쉬움 코드 수정량 많아짐 'Backend' 카테고리의 다른 글
[Backend] MQ (0) 2025.05.05 [Backend] CloudWatch 이론 (0) 2025.04.29 [Backend] Grafana Loki (0) 2025.03.06 [Backend] gRPC (1) 2025.02.28 [Backend] MySQL에서 한글 검색을...? (0) 2025.02.06 다음글이전글이전 글이 없습니다.댓글
스킨 업데이트 안내
현재 이용하고 계신 스킨의 버전보다 더 높은 최신 버전이 감지 되었습니다. 최신버전 스킨 파일을 다운로드 받을 수 있는 페이지로 이동하시겠습니까?
("아니오" 를 선택할 시 30일 동안 최신 버전이 감지되어도 모달 창이 표시되지 않습니다.)