1. OpenFeign이란?
OpenFeign이란 Spring Cloud에서 제공하는 선언적 HTTP 클라이언트이다.
마치 인터페이스를 정의하듯이 API 호출을 할 수 있는 라이브러리입니다.
기존 RestTemplate이나 WebClient와 다르게, 인터페이스만 정의하면 자동으로 구현체를 만들어 주기 때문에 코드가 깔끔하고 유지보수가 편리하다.
2. OpenFeign을 사용하는 이유
1) 인터페이스만 정의하면 API 호출 가능
기존 RestTemplate은 다음과 같이 직접 HTTP 요청을 생성해야 한다.
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://localhost:8081/api/data", String.class);
매번 URL을 직접 입력해야하고, 코드가 복잡하다..
근데 OpenFeign을 사용한다면?
@FeignClient(name = "other-service", url = "http://localhost:8081")
public interface OtherServiceClient {
@GetMapping("/api/data")
String getData();
}
인터페이스만 선언하면 자동으로 구현된다!
2) 마이크로서비스 환경에서 매우 유용
OpenFeign은 마이크로서비스 아키텍처(MSA)에서 강력한 장점을 가진다.
- 서비스가 많아질수록 API 호출을 일일이 관리하기 힘든데, OpenFeign은 자동으로 관리해준다.
- Eureka, Ribbon과 연동하면 서비스 이름만으로 API 호출이 가능하다.
- API 변경 시, 인터페이스만 수정하면 되므로 유지보수가 편리하다.
3) 코드가 짧고 가독성이 좋다
3. OpenFeign 사용법
1) 의존성 추가
dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
}
2) FeignClient 인터페이스 생성
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@FeignClient(name = "other-service", url = "http://localhost:8081")
public interface OtherServiceClient {
@GetMapping("/api/data")
String getData();
@PostMapping("/api/send")
String sendData(@RequestBody String requestData);
}
3) 서비스에서 OpenFeign 사용
import org.springframework.stereotype.Service;
@Service
public class ApiService {
private final OtherServiceClient otherServiceClient;
public ApiService(OtherServiceClient otherServiceClient) {
this.otherServiceClient = otherServiceClient;
}
public String fetchData() {
return otherServiceClient.getData();
}
public String sendData(String requestData) {
return otherServiceClient.sendData(requestData);
}
}
4) OpenFeign 활성화 (@EnableFeignClients)
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableFeignClients
public class FeignConfig {
}
5. 결론
API 호출이 많아질수록 OpenFeign이 편하다!
'Spring' 카테고리의 다른 글
MSA의 동기적 (Synchronous) 통신 (0) | 2025.02.28 |
---|---|
MSA란? (0) | 2025.02.27 |
낙관적 락과 비관적 락 (0) | 2025.02.26 |
Spring Boot에서 Kafka 설정하기! (0) | 2025.02.19 |
Spring Boot + Gradle 멀티 모듈 프로젝트 설정 (0) | 2025.02.18 |