[Spring] open feign으로 http client 통신하기 (2)

들어가며

저번에 작성했던 open feign에서 간단하게 셋팅해서 서버와 클라이언트 간에 통신하는 방법에 대해서만 정리하였는데, 이번에는 error가 발생했을 때 어떻게 핸들링할지랑 재시도하는 방법에 대해서 정리해 본다.

Retryer

@Bean
fun retryer(): Retryer {
    return Retryer.Default(1000, 60000, 10)
}
  • 기본적으로 feign에서는 default Retry 정책이 NEVER_RETRY로 되어 있어 retry가 필요한 경우 bean을 등록해주어야 한다.
  • Default Retryer는 period, maxPeriod, maxAttempts의 파라메터를 받도록 되어 있다.
  • retry를 period 간격 마다 실시하는 것이 아니라 계산된 값에 의해서 시도하게 되어진다.
long nextMaxInterval() {
    long interval = (long) (period * Math.pow(1.5, attempt - 1));
    return interval > maxPeriod ? maxPeriod : interval;
}

Error Decoder

@Bean
fun decoder(): ErrorDecoder {
    return ErrorDecoder { methodKey, response ->
      if (HttpStatus.valueOf(response.status()).is5xxServerError) {
          throw RetryableException(response.status(), response.reason(), Request.HttpMethod.GET, Date(), response.request())
      }
      throw RuntimeException()
    }
}
  • ErrorDecoder의 경우 ErrorDecoder.Default가 구현되어 있음
  • headerRetry-After에 date 값을 전달 해줘야 RetryableException을 던지게 되어 있고 그 외는 exception을 throw하게 되어 있다.
  • StatusCode를 보고 retry를 하고 싶다면 직접 ErrorDecoder를 구현 후 bean으로 등록 하면 된다.
  • exception을 throw하고 있기 때문에 error 발생시 이어서 작업을 하고 싶다면, try/catch를 통해서 error에 대해서 처리를 해줘야 한다

마치며

open feign을 정리해보면서 기본적인 기능들을 다 제공하고 있고 쉽게 커스텀할 수 있는게 장점인 것 같다.

참고


Open Feign 관련 example code는 github에 올려두었으니 참고~!

Leave a comment