JVM/Spring

[SPRING] feign은 뭘까?

Hyo Kim 2021. 4. 18. 22:06
728x90
반응형

netflix

🤔 서론

다른 서버와 통신을 하기 위한 API 를 설계 및 개발을 하면서 알게 된

feign에 대해서 정리하기 위해 작성하게 되었다.

그 전까지는 spring에서 다른 서버를 호출해본 적이 없었기 때문에 어떻게 하는지에 대한 궁금증이 있었는데

이번 기회에 알게 될 수 있었다.


🤷‍♂️ feign은 그래서 뭔데!

 

- Netflix에서 만든 HTTP client binder로서 기존 http client 작성을 쉽게 만들어주는 라이브러리이다.

 

- interface를 작성하고 annotation을 붙여서 쉽게 사용할 수 있기 때문에,

HTTP API를 균일하게 바인딩하여 복잡성을 줄여준다.

 

- 이전에는 RestTemplate 방식과 WebClient 방식이 존재했지만

현재 스프링 커뮤니티에서는 RestTemplate사용을 권장하지 않는다.

 

아래 간단한 예시를 통해서 간단한 사용방법을 알려드리겠습니다.


1. 의존성 추가

- maven

<properties>
    <spring.cloud-version>Hoxton.SR8</spring.cloud-version>
</properties>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring.cloud-version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

 

- gradle

buildscript {
  dependencies {
    classpath "io.spring.gradle:dependency-management-plugin:1.0.10.RELEASE"
  }
}

ext {
  set('springCloudVersion', "Hoxton.SR8")
}


apply plugin: "io.spring.dependency-management"

dependencyManagement {
  imports {
    mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
  }
}

2. Application

@SpringBootApplication
@EnableFeignClients
public class Application {

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

}

@EnableFeignClients 어노테이션이 지정된 package들을 돌아다니면서 @FeignClient 어노테이션을 찾아

구현체를 만들어 줍니다.


3. 인터페이스 작성

@FeignClient(name = "stores", configuration = FooConfiguration.class, url = "${feign.url}")
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);
}

 

- @feignClient 어노테이션을 통해 feign을 사용하는 인터페이스라고 알려줍니다.

- configuration 옵션을 통해 default설정 값을 override를 할 수 있습니다.

- url 옵션을 통해 불러올 url을 셋팅해줍니다.


4. 서비스 작성

@Service
public class StoreService {
    @Autowired
    StoreClient storeClient;

    public List<Store> getStores() {
        return storeClient.getStores();
    }
}

- @Autowired를 통해 clinet를 의존성 주입을 해줍니다.

- getSotres()를 호출하여 feignClient를 호출합니다.

 


✨후기

위는 아주 간단하게 진짜 Feign을 사용하는 방법만을 설명하였습니다.

더욱 상세하게 사용하고 싶다면, 공식문서를 살펴보는 것도 좋은 방법인 것 같습니다.

---

다른 API를 호출하는 방법이 생각보다 간단해서 놀랐습니다.

Feign 이전에 사용했던 방식은 이 방식보다 좀 더 복잡하다고 들었는데,

어떻게 했었는지에 대한 궁금증이 생겨 한 번 찾아봐야겠습니다.

 

참고, 인용사이트

https://woowabros.github.io/experience/2019/05/29/feign.html
https://sabarada.tistory.com/115
https://supawer0728.github.io/2018/03/11/Spring-Cloud-Feign/
https://velog.io/@skyepodium/2019-10-06-1410-%EC%9E%91%EC%84%B1%EB%90%A8
https://docs.spring.io/spring-cloud-openfeign/docs/current/reference/html/
728x90
반응형