Today
-
Yesterday
-
Total
-
  • Spring Boot: Retry
    Spring Boot 🍃 2023. 12. 9. 00:01

    보고 배운 블로그: wonyong-jang.github


    API 서비스의 재처리에 대한 고민

    API 사용시 시스템 안정성을 높이기 위해 재처리를 어떻게 처리할까에 대한 고민을 해야한다.


    재처리를 할 때는 보통 다음 사항들에 대해 고려해보게 된다.

    • 재시도를 몇 번 실행할 것인가?
    • 재시도 하기 전에 지연 시간을 얼마나 줄 것인가?
    • 재시도를 모두 실패했을 경우 어떻게 처리할 것인가?

    Spring Retry 를 사용하는 방법으로는

    Annotation을 사용하는 방법과 RetryTemplate을 사용하는 방법이 있다.


    자세히 알려주는 블로그: wonyong-jang.github



    Retry 실습

    어노테이션을 사용하는 방법에 대해서만 실습 !

    의존성 추가

    //  Spring Retry 
        implementation 'org.springframework.retry:spring-retry'
    
    //  mock web server : test 를 위함
        testImplementation 'com.squareup.okhttp3:okhttp:4.10.0'
        testImplementation 'com.squareup.okhttp3:mockwebserver:4.10.0'

    Retry Config 작성

    /config/RetryConfig.java

    @EnableRetry
    @Configuration
    public class RetryConfig {
    
    }

    만약 , RetryRemplate을 사용하려고 한다면 이 클래스 안에 아래의 내용을 작성해볼 수 있다.

    @Bean
    public RetryTemplate retryTemplate() {
    	return new RetryTemplate();
    }

    @Retryable 사용

    api 를 호출하는 메서드에 @Retryable 메서드를 작성해주면 해당 메서드에서 api 호출 실패시 동작할 내용들을 지정해주게 된다.

    @Retryable(
            value = RuntimeException.class, // 재시도 할 예외 지정
            maxAttempts = 2, // 최대 재시도 수행 횟수
            backoff = @Backoff(delay = 2000) // 딜레이 시간 지정
    )
    public KakaoApiResponseDto requestAddressSearch(String address) {
    
        if (ObjectUtils.isEmpty(address)) return null;
    
        URI uri = kakaoUriBuilderService.buildUriByAddressSearch(address);
    
        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.AUTHORIZATION, kakaoRestApiKey);
        HttpEntity httpEntity = new HttpEntity<>(headers);
    
        // kakao api 호출
        return restTemplate.exchange(uri, HttpMethod.GET, httpEntity, KakaoApiResponseDto.class).getBody();
    }

    @Recover 사용

    @Retryable 메서드가 모두 호출 실패한 경우에 실행 될 메서드.

    주의할 점은 반환타입을 @Retryable이 붙은 메서드와 같게 해주어야 한다.

    @Recover
    public KakaoApiResponseDto recover(RuntimeException e, String address) {
        log.error("All the retires failed. address: {}, error : {}", address, e.getMessage());
        return null;
    }

    정말 자세히 알려주는 블로그: wonyong-jang.github

Designed by Tistory / Custom by 얼거스