Feign 이란?
- Feign은 Netflix에서 개발된 Http Client Binder 입니다.
- 웹 서비스 클라이언트를 보다 쉽게 작성할 수 있습니다.
- Spring Data JPA를 사용하는 것 처럼, 추상화를 통해 구현체를 작성하지 않고 Interface만 작성하면, 자동으로 구현됩니다.
- RestTemplate보다 훨씬 간결합니다.
- RestTemplate은 대체되고 있기 때문에 주의해서 사용해야 합니다.
- MSA로 시스템 아키텍처가 많이 변경되면서 SRP로 많은 개선점을 보였지만,
API의 호출이 증가하였습니다.
API의 호출 증가에 따라, API 호출 코드를 작성하는 것은 극심한 피로가 되었고,
이를 해결할 수 있는 Spring Cloud 프로젝트가 바로 Feign 입니다.
Spring Cloud에는 여러 장애상황에 대해 견딜 수 있도록 도와주는 Hystrix와
L4 Switch 하드웨어 장비처럼 로드밸런싱을 해주며 Client Side인 Ribbon 등이 있습니다.
의존성(Dependency)
build.gradle
ext {
set('springCloudVersion', "2021.0.5")
}
implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
예제
Main
@EnableFeignClients
@SpringBootApplication
public class FeignTest {
public static void main(String[] args) {
SpringApplication.run(FeignTest.class, args);
}
}
@EnableFeignClients
- @EnableFeignClients는 @SpringBootApplication 하위 경로에 선언합니다.
- @EnableFeignClients는 하위 경로의 @FeignClient를 Scan합니다.
- @ComponentScan과 비슷하게 이해하시면 됩니다.
Controller
@RestController
@RequestMapping("/testget")
public class TestGetController {
@Autowired
TestService testService;
@GetMapping("/start")
public String testStartHandle() {
return testService.callTestGetFeign("이 string 은 잘 갑니까?");
}
@GetMapping("/get/{string}")
public String testTargetHandle(@PathVariable("string") String string) {
return string + "을 받았습니다.";
}
}
public String testStartHandle()
- Service를 통해 "이 string 은 잘 갑니까?"를 GET 쿼리 스트링으로 보냅니다.(해당 Handler의 @GetMapping 선언과 관련 없습니다.)
- 해당 Message를 Service > Repository > Feign 으로 타고 들어가서 Request를 보내게 됩니다.
public String testTargetHandle(@PathVariable("string") String string)
- Feign을 통해서 Request를 받는 Handler 입니다.
- 쿼리 스트링으로 받은 "이 string 은 잘 갑니까?" + "을 받았습니다."를 출력해줍니다.
Service
@Service
public class TestService {
@Autowired
TestClient testClient;
public String callTestGetFeign(String string) {
return testClient.testGetFeign(string);
}
}
public interface TestClient
@FeignClient(value = "test1", url = "http://localhost:8090")
public interface TestClient {
@GetMapping("/testget/get/{string}")
String testGetFeign(@PathVariable("string") String string);
}
@FeignClient
- value : FeignClient의 서비스 이름으로, 필수 속성입니다. BeanName과는 다릅니다.
- url : 해당 Interface의 baseUrl 입니다.
- Class 레벨에서 @RestMapping으로 Handler들을 묶어주는 것과 비슷하다고 생각하시면 됩니다.
- configuration : 본문에 없습니다. 관련 커스터마이징 Configuration을 설정할 수 있습니다.
- qualifier : 추가 구분자를 설정해줍니다.
- fallback : Hystrix fallback 메서드입니다.
String testGetFeign(@PathVariable("string") String string)
- http://localhost:8090/testget/get/{string}으로 GET Request를 보냅니다.
- "이 string 은 잘 갑니까?"을 string 파라미터 변수로 받아서 쿼리 스트링으로 Request에 실어 보냅니다.
댓글