-
http client로 Open feign 사용하기카테고리 없음 2020. 8. 5. 21:15
스프링에서는 RestTemplate 을 주로 사용하지만 다른 선택지들도 많다.
OpenFeign
https://github.com/OpenFeign/feign
OpenFeign/feign
Feign makes writing java http clients easier. Contribute to OpenFeign/feign development by creating an account on GitHub.
github.com
RestTemplate과 비교하자면 http 요청을 하는 모양새가 좀 더 보기 편해진다.
예를 들어 깃허브 owner와 repository를 파라미터로 넘겨 contributor 목록을 받아오는 api 는 아래 처럼 선언이 가능하다.
(예제는 코틀린으로 쓰였습니다)
interface GitHub { @RequestLine("GET /repos/{owner}/{repo}/contributors") fun contributors(@Param("owner") owner: String, @Param("repo") repo: String): List<Contributor> }
자세한 내용은 뒤로 하더라도 어떤 방식으로 GET 요청을 만들어 사용하는지 딱 봐도 알기가 쉽다.
요즘엔 비슷한 방식으로 http client를 손쉽게 작성하는 라이브러리들이 많이 나와 있지만 그 중에서 Feign을 추천하는 이유는 필요한 기능을 왠만큼 갖추고 있기 때문이다.
- logging
- interceptor
- error handling
- network configuration through 'apache http client'
- retry
- async
- client load balancing (with spring)
- response caching
- etc...
인터페이스의 작성방식이 편리하다는 것 이외에 왠만큼 필요한 기능은 다 가지고 있다고 무방하다. 또한 스프링의 선택을 받은 라이브러리이기 때문에 스프링쪽의 feign 공식 문서를 보면 더 다양한 기능을 탑재하여 사용할 수 있는 것 같다.
https://cloud.spring.io/spring-cloud-openfeign/reference/html/#netflix-feign-starter
Spring Cloud OpenFeign
Feign is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it. It has pluggable annotation support including Feign annotations and JAX-RS annotations. Feign also supports pluggable
cloud.spring.io
코드로 돌아와 설정 부분을 조금 더 살펴보고 맛보기는 마무리 해도 될 것 같다.
fun githubAdapter(): GitHub = Feign.builder() .errorDecoder(SimpleErrorDecoder()) .decoder(JacksonDecoder(ObjectMapper() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .registerModule(KotlinModule()))) .target(GitHub::class.java, "https://api.github.com")
encode, decode는 jackson, gson 등 모듈을 갈아 끼울 수 있게 제공하고 있고, 인터페이스의 메서드 호출이기 때문에 http status code 등을 어떻게 얻어오지? 하는 부분에 있어서는 errorDecoder를 사용하면 된다.
그리고 마지막 target 부분에 선언한 인터페이스와 도메인을 넣게 되면 구현체인 githubAdapter 가 생성된다.
class SimpleErrorDecoder : ErrorDecoder { override fun decode(methodKey: String?, response: Response): Exception = when (response.status()) { in 400..499 -> SimpleException(response.status(), response.reason()) in 500..599 -> SimpleException(response.status(), response.reason()) else -> errorStatus(methodKey, response) } }
ErrorDecode 인터페이스를 직접 구현하면 위의 코드처럼 status 들을 얻어올 수 있다.
짧게 알아본 OpenFeign 관심이 있다면 도입을 해봐도 좋을 것 같다. 추천!