반응형
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 |