728x90

이번 포스팅에서는 OpenFeign 통합을 통해 Spring 환경과 다른 Spring 프로그래밍 모델에서의 자동구성과 바인딩을 해보도록 하겠습니다. 

 

1.  선언적 REST Client: Feign

Feign은 선언적 웹 서비스 클라이언트로 web service client를 쉽게 해줍니다.

먼저, Feign을 사용하려면 인터페이스를 만들고 주석을 달아야 합니다. Feign annotation과 JAX-RS annotation을 포함한 플러그형 주석을 제공합니다. Feign은 플러그형 인코더와 디코더를 지원합니다.

Spring Cloud는 Spring MVC annotation과 Spring web에서 HttpMessageConverters와 같이 사용하기 위해 추가합니다. Spring Cloud는 Feign을 사용할 때 부하 분산 http 클라이언트를 제공하기 위해 Eureka, Spring Cloud CircuitBreaker, Spring Clould LoadBalancer를 통합합니다.

 

1.1 Feign 사용법

Feign을 프로젝트에 사용하기 위해 org.springframework.cloudartifact id spring-cloud-starter-openfeign을 포함합니다. 

 

spring boot app 예제

@SpringBootApplication
@EnableFeignClients
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

 

 

StoreClient.java

@FeignClient("stores")
public interface StoreClient {
    @RequestMapping(method = RequestMethod.GET, value = "/stores")
    List<Store> getStores();

    @RequestMapping(method = RequestMethod.GET, value = "/stores")
    Page<Store> getStores(Pageable pageable);

    @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
    Store update(@PathVariable("storeId") Long storeId, Store store);

    @RequestMapping(method = RequestMethod.DELETE, value = "/stores/{storeId:\\d+}")
    void delete(@PathVariable Long storeId);
}

@FeignClient annotation에서 String value("sotres" above)는 임의의 클라이언트 이름으로, Spring Cloud LoadBalnacer 클라이언트를 생성하는 데 사용됩니다. URL 속성(절대값 또는 호스트이름)을 사용하여 지정할 수도 있습니다. application context에서 bean의 이름은 인터페이스의 정규화된 이름입니다. 원하는 alias를 지정하기 위해서는 @FeignClient annotation의 qualifiers 값을 사용하면 됩니다.

 

load-balancer client는 "stores"서비스에 대한 물리적 주소를 알아내고자 할 것입니다. Eureka 클라이언트의 경우 Eureka 서비스 레지스트리에서 서비스를 확인합니다. Eureka를 사용하지 않으려면 SimpleDiscoveryClient를 사용하여 외구 구성에서 서버 목록을 구성할 수 있습니다.

 

Spring Clould OpenFeign은 Spring Clould LoadBalancer의 차단모드에서 사용가능한 모등기능을 지원합니다. 이는 프로젝트 설명서에서 자세히 알아볼 수 있습니다.(https://docs.spring.io/spring-cloud-commons/docs/current/reference/html/#spring-cloud-loadbalancer)

 

1.1.1 Attrivute resolution mode

Feign client bean을 생성하는 동안 @FeignClient 주석을 통해 전달된 값을 확인합니다. 4.x부터 즉시 확인가능하고 대부분의 사용 사례에 적합한 솔루션이며 AOT 지원도 가능합니다. 속성을 지연되는 경우 spring.cloud.openfeign.lazy-attributes-resolution property 값을 true로 변경해 보세요.

728x90
반응형

+ Recent posts